ichenpipi/unity-code-executor

还未处理需要引入命名空间的情况

Bian-Sh opened this issue · 1 comments

比如下面这个代码,需要用到 System.Diagnostics 命名空间

                string resPath = "";
                StackFrame[] stackFrames = new StackTrace(true).GetFrames();
                if (stackFrames != null && stackFrames.Length > 0)
                {
                    string scriptPath = stackFrames[0].GetFileName()?.Replace("\\", "/");
                    if (!string.IsNullOrEmpty(scriptPath))
                    {
                        int projectPathLength = Application.dataPath.Length - "Assets".Length;
                        int lastSlashIndex = scriptPath.LastIndexOf("/");
                        resPath = scriptPath.Substring(projectPathLength, lastSlashIndex - projectPathLength) + "/Res/";
                        Debug.Log($"res path = {resPath}");
                    }
                }

否则就会报错了:

The type or namespace name `StackFrame' could not be found. Are you missing `System.Diagnostics' using directive?
UnityEngine.Debug:LogError (object)
ChenPipi.CodeExecutor.Example.InjectHelperCSharp:CompileCode (string) (at E:/Unity/Github/unity-code-executor/Editor/Scripts/Examples/InjectHelperCSharp.cs:198)
以下省略...

针对没有默认引入的命名空间,可以直接在代码中以完整名称(命名空间全称+类名)的方式来引用,如下:

string resPath = "";
System.Diagnostics.StackFrame[] stackFrames = new System.Diagnostics.StackTrace(true).GetFrames();
if (stackFrames != null && stackFrames.Length > 0)
{
    string scriptPath = stackFrames[0].GetFileName()?.Replace("\\", "/");
    if (!string.IsNullOrEmpty(scriptPath))
    {
        int projectPathLength = Application.dataPath.Length - "Assets".Length;
        int lastSlashIndex = scriptPath.LastIndexOf("/");
        resPath = scriptPath.Substring(projectPathLength, lastSlashIndex - projectPathLength) + "/Res/";
        Debug.Log($"res path = {resPath}");
    }
}

主要修改如下:

  • StackFrame => System.Diagnostics.StackFrame
  • StackTrace => System.Diagnostics.StackTrace