找不到类型或名称空间名称"UnityEditor" [英] The type or namespace name `UnityEditor' could not be found

查看:181
本文介绍了找不到类型或名称空间名称"UnityEditor"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我纠正此问题.

Assets/Menu.cs(97,73):警告CS0618:UnityEditor.EditorUtility.GetAssetPath(UnityEngine.Object)' is obsolete:使用AssetDatabase.GetAssetPath'

Assets/Menu.cs(97,73): warning CS0618: UnityEditor.EditorUtility.GetAssetPath(UnityEngine.Object)' is obsolete:Use AssetDatabase.GetAssetPath'

由于脚本存在编译器错误而导致构建Player出错

Error building Player because scripts had compiler errors

资产/Menu.cs(2,7):错误CS0246:找不到类型或名称空间名称'UnityEditor'.您是否缺少using指令或程序集引用?

Assets/Menu.cs(2,7): error CS0246: The type or namespace name `UnityEditor' could not be found. Are you missing a using directive or an assembly reference?

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

struct ObjMaterial
{
    public string name;
    public string textureName;
}

public class Menu : MonoBehaviour { 

    public int window; 

    void Start () { 
        window = 1;

    } 

    private static int vertexOffset = 0;
    private static int normalOffset = 0;
    private static int uvOffset = 0;


    //User should probably be able to change this. It is currently left as an excercise for
    //the reader.
    private static string targetFolder = "ExportedObj";


    private static string MeshToString(Component mf, Dictionary<string, ObjMaterial> materialList) 
    {



        Mesh m;
        Material[] mats;

        if(mf is MeshFilter)
        {
            m = (mf as MeshFilter).mesh;
            mats = mf.GetComponent<Renderer>().sharedMaterials;
        }
        else if(mf is SkinnedMeshRenderer)
        {
            m = (mf as SkinnedMeshRenderer).sharedMesh;
            mats = (mf as SkinnedMeshRenderer).sharedMaterials;
        }
        else
        {
            return "";
        }

        StringBuilder sb = new StringBuilder();

        sb.Append("g ").Append(mf.name).Append("\n");
        foreach(Vector3 lv in m.vertices) 
        {
            Vector3 wv = mf.transform.TransformPoint(lv);

            //This is sort of ugly - inverting x-component since we're in
            //a different coordinate system than "everyone" is "used to".
            sb.Append(string.Format("v {0} {1} {2}\n",-wv.x,wv.y,wv.z));
        }
        sb.Append("\n");

        foreach(Vector3 lv in m.normals) 
        {
            Vector3 wv = mf.transform.TransformDirection(lv);

            sb.Append(string.Format("vn {0} {1} {2}\n",-wv.x,wv.y,wv.z));
        }
        sb.Append("\n");

        foreach(Vector3 v in m.uv) 
        {
            sb.Append(string.Format("vt {0} {1}\n",v.x,v.y));
        }

        for (int material=0; material < m.subMeshCount; material ++) {
            sb.Append("\n");
            sb.Append("usemtl ").Append(mats[material].name).Append("\n");
            sb.Append("usemap ").Append(mats[material].name).Append("\n");

            //See if this material is already in the materiallist.
            try
            {
                ObjMaterial objMaterial = new ObjMaterial();

                objMaterial.name = mats[material].name;


                objMaterial.textureName = EditorUtility.GetAssetPath(mats[material].mainTexture);
                //else 
                    //objMaterial.textureName = null;

                materialList.Add(objMaterial.name, objMaterial);
            }
            catch (ArgumentException)
            {
                //Already in the dictionary
            }


            int[] triangles = m.GetTriangles(material);
            for (int i=0;i<triangles.Length;i+=3) 
            {
                //Because we inverted the x-component, we also needed to alter the triangle winding.
                sb.Append(string.Format("f {1}/{1}/{1} {0}/{0}/{0} {2}/{2}/{2}\n", 
                    triangles[i]+1 + vertexOffset, triangles[i+1]+1 + normalOffset, triangles[i+2]+1 + uvOffset));
            }
        }

        vertexOffset += m.vertices.Length;
        normalOffset += m.normals.Length;
        uvOffset += m.uv.Length;

        return sb.ToString();
    }

    private static void Clear()
    {
        vertexOffset = 0;
        normalOffset = 0;
        uvOffset = 0;
    }

    private static Dictionary<string, ObjMaterial> PrepareFileWrite()
    {
        Clear();

        return new Dictionary<string, ObjMaterial>();
    }

    private static void MaterialsToFile(Dictionary<string, ObjMaterial> materialList, string folder, string filename)
    {
        using (StreamWriter sw = new StreamWriter(folder + "/" + filename + ".mtl")) 
        {
            foreach( KeyValuePair<string, ObjMaterial> kvp in materialList )
            {
                sw.Write("\n");
                sw.Write("newmtl {0}\n", kvp.Key);
                sw.Write("Ka  0.6 0.6 0.6\n");
                sw.Write("Kd  0.6 0.6 0.6\n");
                sw.Write("Ks  0.9 0.9 0.9\n");
                sw.Write("d  1.0\n");
                sw.Write("Ns  0.0\n");
                sw.Write("illum 2\n");

                if (kvp.Value.textureName != null)
                {
                    string destinationFile = kvp.Value.textureName;


                    int stripIndex = destinationFile.LastIndexOf('/');//FIXME: Should be Path.PathSeparator;

                    if (stripIndex >= 0)
                        destinationFile = destinationFile.Substring(stripIndex + 1).Trim();


                    string relativeFile = destinationFile;

                    destinationFile = folder + "/" + destinationFile;

                    Debug.Log("Copying texture from " + kvp.Value.textureName + " to " + destinationFile);

                    try
                    {
                        //Copy the source file
                        File.Copy(kvp.Value.textureName, destinationFile);
                    }
                    catch
                    {

                    }   


                    sw.Write("map_Kd {0}", relativeFile);
                }

                sw.Write("\n\n\n");
            }
        }
    }

    private static void MeshToFile(Component mf, string folder, string filename) 
    {
        Dictionary<string, ObjMaterial> materialList = PrepareFileWrite();

        using (StreamWriter sw = new StreamWriter(folder +"/" + filename + ".obj")) 
        {
            sw.Write("mtllib ./" + filename + ".mtl\n");

            sw.Write(MeshToString(mf, materialList));
        }

        MaterialsToFile(materialList, folder, filename);
    }

    private static void MeshesToFile(Component[] mf, string folder, string filename) 
    {
        Dictionary<string, ObjMaterial> materialList = PrepareFileWrite();

        using (StreamWriter sw = new StreamWriter(folder +"/" + filename + ".obj")) 
        {
            sw.Write("mtllib ./" + filename + ".mtl\n");

            for (int i = 0; i < mf.Length; i++)
            {
                sw.Write(MeshToString(mf[i], materialList));
            }
        }

        MaterialsToFile(materialList, folder, filename);
    }

    private static bool CreateTargetFolder()
    {
        try
        {
            System.IO.Directory.CreateDirectory(targetFolder);
        }
        catch
        {
            //EditorUtility.DisplayDialog("Error!", "Failed to create target folder!", "");
            return false;
        }

        return true;
    }



    void OnGUI () { 
        GUI.BeginGroup (new Rect (Screen.width / 2 - 100, Screen.height / 2 - 100, 200, 200)); 
        if(window == 1) 
        { 
            if(GUI.Button (new Rect (10,30,180,30), "Экспортировать")) 
            { 

                if (!CreateTargetFolder())
                    return;

                //GameObject[] gos = GameObject.FindGameObjectsWithTag("Boat");
                //Selection.objects = gos;

                GameObject[] selection = GameObject.FindGameObjectsWithTag("Boat");
                //Transform[] selection = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);

                if (selection.Length == 0)
                {
                    //EditorUtility.DisplayDialog("No source object selected!", "Please select one or more target objects", "");
                    return;
                }

                int exportedObjects = 0;

                ArrayList mfList = new ArrayList();

                for (int i = 0; i < selection.Length; i++)
                {
                    Component[] meshfilter = selection[i].GetComponentsInChildren(typeof(MeshFilter)).Concat(selection[i].GetComponentsInChildren(typeof(SkinnedMeshRenderer))).ToArray();

                    for (int m = 0; m < meshfilter.Length; m++)
                    {
                        exportedObjects++;
                        mfList.Add(meshfilter[m]);
                    }
                }

                if (exportedObjects > 0) 
                {
                    Component[] mf = new Component[mfList.Count];

                    for (int i = 0; i < mfList.Count; i++) {
                        mf [i] = (Component)mfList [i];
                    }

                    string filename = /*EditorApplication.currentScene +*/ "_" + exportedObjects;

                    int stripIndex = filename.LastIndexOf ('/');//FIXME: Should be Path.PathSeparator

                    if (stripIndex >= 0)
                        filename = filename.Substring (stripIndex + 1).Trim ();

                    MeshesToFile (mf, targetFolder, filename);

                }

            } 

            if(GUI.Button (new Rect (10,150,180,30), "Выход")) 
            { 
                window = 5; 
            } 
        } 

        if(window == 5) 
        { 
            GUI.Label(new Rect(50, 10, 180, 30), "Вы уже выходите?");   
            if(GUI.Button (new Rect (10,40,180,30), "Да")) 
            { 
                Application.Quit(); 
            } 
            if(GUI.Button (new Rect (10,80,180,30), "Нет")) 
            { 
                window = 1; 
            } 
        } 
        GUI.EndGroup (); 
    } 
} 

推荐答案

在使用任何Unity API之前,检查API名称空间非常重要.如果名称空间来自UnityEditor,则只能在编辑器中使用.这用于制作编辑器插件.您不能在构建中使用它,并且在为任何平台构建时都会抛出错误.

Before using any Unity API, it is very important to check the API namespace. If the namespace is from UnityEditor then it is only meant to work in the Editor only. This is used to make an Editor plugin. You can't use it in a build and it will throw an error when building for any platform.

根据文档 AssetDatabase

According the docs, AssetDatabase and EditorUtility class are from the UnityEditor namespace.

您必须重新设计游戏才能使用GetAssetPath功能.您绝对可以在没有该功能的情况下制作游戏.我不清楚您在做什么,但您应该查看 Resources 类.这将帮助您在运行时加载GameObject.

You have to re-design your game to work without the GetAssetPath function. You can definitely make a game without that function. I can't tell what you are doing but you should look into the Resources class. This will help you load your GameObjects during run-time.

要解决当前的问题,

替换

using UnityEditor;

使用

#if UNITY_EDITOR
using UnityEditor;
#endif

然后替换

objMaterial.textureName = EditorUtility.GetAssetPath(mats[material].mainTexture);

使用

        objMaterial.textureName = "";
#if UNITY_EDITOR
        objMaterial.textureName = EditorUtility.GetAssetPath(mats[material].mainTexture);
#endif

您还可以将Menu脚本放在Assets/Editor目录中的文件夹中,但是请理解,这不能解决代码无法在内部版本中工作的问题.它将仅允许您构建项目,而不会在您的问题中出现这些错误. UnityEditor名称空间中的类仅用于Editor插件.

You can also put your Menu script in a folder in the Assets/Editor directory but please understand that this does not solve the problem that your code won't work in a build. It will only allow your project to build without those errors in your question. The classes from the UnityEditor namespace are only used for Editor plugin.

这篇关于找不到类型或名称空间名称"UnityEditor"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆