如何在运行时编译的 C# 代码中使用 "UnityEngine"?

How to use "UnityEngine" in runtime-compiled C# code?

我正在尝试使用 C#、Unity 和 this tutorial 在运行时编译代码。我什么都有 运行,但希望能够在伪代码中使用像 Debug.Log(); 这样的 UnityEngine 方法。为了这样做,我在里面写了using UnityEngine;,但是得到了以下错误:

The type or namespace name "UnityEngine" could not be found. Are you missing an assembly reference?

我该如何解决这个问题?

我尝试将 UnityEngine 的引用添加到 CompilerParameters.ReferencedAssemblies,如下所示:

//parameters is of type CompilerParameters
parameters.ReferencedAssemblies.Add("UnityEngine.dll");

但这给了我以下错误:

Metadata file UnityEngine.dll could not be found.

这是我的代码中最相关的部分,但您无法像那样重现它。相反,从 above mentioned 教程中获取代码。

public void Compile()
{
  string code = @"
    using UnityEngine;
    namespace First
  {
    public class Program
    {
      public static void Main()
      {
            " + "Debug.Log(\"Test!\");" + @"
      }
    }
  }
";
  CSharpCodeProvider provider = new CSharpCodeProvider();
  CompilerParameters parameters = new CompilerParameters();
  parameters.ReferencedAssemblies.Add("UnityEngine.dll");
}

由于我对 C# 没有经验,并且只在 Unity 中使用它,所以我不知道什么是 .dll 文件,并且在修复此问题时不知道从哪里开始。我非常感谢任何形式的帮助!

你应该把 UnityEngine.dll 的 path 放在那里,而不仅仅是 UnityEngine.dll,除非它存在于工作目录中,这是高度不太可能。

根据 this answer,您可以轻松地在文件系统中找到 UnityEngine.dll(以及其他 dll)。它在Editor\Data\Managed下面,所以你应该写:

parameters.ReferencedAssemblies.Add(@"C:\path\to\your\unity\installation\Editor\Data\Managed\UnityEngine.dll");

我尝试了一些开源解决方案,但找不到适用于所有 3 个平台的解决方案。最后我买了这个资产,它在 Windows、Mac 和 Linux 上没有问题:https://assetstore.unity.com/packages/tools/integration/dynamic-c-82084 文档和支持非常好。例如,我有一个问题,我无法编译使用 Unity Screen class 的 class,支持人员告诉我必须在设置页面中包含 UnityEngine.CoreModule.dll解决问题的资产。

PS:我没有因为这个推荐而得到钱,我只是这个资产的快乐用户。