[Unity][代码问题]The type or namespace name `AssetDatabase' does not exist in the namespace `UnityEditor

unity 出现问题  The type or namespace name `AssetDatabase' does not exist in the namespace `UnityEditor'. Are you missing an assembly reference?

参考资料1解决办法


使用UnityEditor库的变量,由于UnityEditor只存在Unity编辑器中,建立EXE的时候,会报错

using UnityEditor;

 应该写为

#if UNITY_EDITOR
using UnityEditor;
#endif

以相关资料1 的出现的错误为例子,进行纠正

 Test_FindFiles.cs的findFiles001()函数中的代码为


        //获得 工程文件的路径,以及要 加载的目标文件夹下面的 文件路径,存放在一个字符串数组中
        string[] arrStrAudioPath = Directory.GetFiles(Application.dataPath + "/123/asset/", "*", SearchOption.AllDirectories);//using System.IO;
        FileInfo file;
        //循环遍历每一个路径,单独加载
        foreach (string strAudioPath in arrStrAudioPath)
        {
            //替换路径中的反斜杠为正斜杠       
            string strTempPath = strAudioPath.Replace(@"\", "/");
            //截取我们需要的路径
            strTempPath = strTempPath.Substring(strTempPath.IndexOf("Assets"));
            #if UNITY_EDITOR
            //根据路径加载资源
            UnityEngine.Object objAudio = UnityEditor.AssetDatabase.LoadAssetAtPath(@strTempPath, typeof(UnityEngine.Object));//using UnityEditor;
//objAudio.GetType();
            if (objAudio != null)
            {
                Debug.Log("  objName: " + objAudio.GetType());//获得 目标文件 的物体类型
                objects.Add(objAudio);
            }

            if (objAudio != null
                && objAudio.GetType().ToString() == "Item")//当文件夹下的文件为Item脚本创建的文件的时候
            {
                items.Add((Item)objAudio);//强制类型转换,放入 Item数组中。

                Type type = objAudio.GetType();//因为using UnityEngine;和using System;都有Object的定义,因此使用UnityEngine.Object来进行区分
                FieldInfo[] fil = type.GetFields();

                foreach (FieldInfo var in fil)//仅能获取到c字段(输出c=2)
                {
                    //Debug.Log("FieldInfo: " + var.Name + "=" + var.GetValue(father_));
                    if (var.Name == "name")//找到 TestSon_1.asset中的 TestStyle类型名字为testStyle的变量
                    {
                        Debug.Log("ItemName:   " + var.GetValue(objAudio));//获得Item类型的.asset文件的name变量
                    }
                }
            }

            #endif

因为Test_FindFiles.cs的findFiles001()函数中的objAudio变量

使用了UnityEditor库。所以要使用


#if UNITY_EDITOR
    //some code here that uses something from the UnityEditor namespace
#endif

来保证正常运行。


相关资料:

1.

 

[Unity]获得目标文件夹下面所有的.asset物体的变量数值

2.

参考资料:

1.

UNITY - The name `AssetDatabase' does not exist in the current context

2.

3.

4.

猜你喜欢

转载自blog.csdn.net/BuladeMian/article/details/104737408