首页 > 解决方案 > 构建统一游戏时出现“当前上下文中不存在名称“资产数据库””错误

问题描述

我的老师给了我一个统一(c#)的挑战,我必须将预制件加载到一个数组中(作为一个GameObject[]函数)。我的代码在编辑器中工作,但是当我构建游戏时,它给了我错误The name "Asset Database" does not exist in the curernt context。我目前的代码是:

using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;
using System;

public class FindCards : MonoBehaviour
{
    public string directoryName;
    public List<GameObject> foundGameObjects;

    public GameObject[] ListOfCards()
    {
        // get the directory and the files in them
        DirectoryInfo dirInfo = new DirectoryInfo(Application.dataPath + directoryName);

        FileInfo[] fileInfo = dirInfo.GetFiles("*.prefab");

        // loop through the files
        foreach(FileInfo file in fileInfo)
        {
            // get the path to the directory again (with proper formatting)
            string fullPath = file.FullName.Replace(@"\","/");
            string assetPath = "Assets" + fullPath.Replace(Application.dataPath, "");
    
    
            GameObject _asset;
            // load the asset from the direcotry
            _asset = AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject)) as GameObject;            

            // add it to the list
            foundGameObjects.Add(_asset);
            Debug.Log(_asset.name);
        }


        // return the list as an array
        return(foundGameObjects.ToArray());
    }

    public void SetCardProperties(string cardName, Card card)
    {
        // get the first string, and the int
        // from the card's name
        string[] sub = cardName.Split('_');

        // (if the name was Diamond_07,     // string name
        // there would be an int = 07 and   // name[0]
        // a string = Diamond)              // name[1]
        card.suit = sub[0];
        Int32.TryParse(sub[1], out card.number);
    }
}

调用此函数的代码如下所示(注意这是在不同的脚本中):

private void Start()
{
    canScore = true;
    gameIsGoing = true;

    // set up cards
    cards = findCards.ListOfCards();

    for (int i = 0; i < cards.Length; i++)
    {
        Card card = cards[i].GetComponent<Card>();

        findCards.SetCardProperties(cards[i].name, card);
    }

    // set up deck
    ResetDeck();
}

这里的目录: 目录中的Prefabs

这里的 错误:统一给我的错误

我一直在拔头发,因为我在网上找不到任何可以帮助我的东西。我的老师给了我这个挑战,因为他也不知道该怎么做,这就是我问这个问题的原因......

提前致谢!

标签: c#unity3d

解决方案


AssetsDatabase 似乎只在编辑器中有效。检查此线程以获取更多信息:

https://answers.unity.com/questions/1068055/assetdatabase.html

编辑:

`Resources.Load()´ 在路径中搜索:“Assets/Resources”。

看看文档是怎么说的:

如果可以在路径中找到资产,则返回 type T,否则返回 null。如果 path 处的文件属于无法转换为 的类型T,也返回 null。该路径相对于项目的 Assets 文件夹中名为 Resources 的任何文件夹。可以使用多个资源文件夹。例如,一个项目可能有名为 Assets/Resources 和 @@AssetsAssetsResources@@ 的资源文件夹。路径不需要在字符串中包含资产和资源,例如在 @@AssetspathShotgun.prefab@@ 加载游戏对象只需要 Shotgun 作为路径。此外,如果存在@@AssetspathMissiles/PlasmaGun.prefab,则可以使用 GunspathPlasmaGun@@ 作为路径字符串来加载它。如果您有多个资源文件夹,则不能重复使用资产名称。


推荐阅读