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

问题描述 投票:0回答:1

我正在尝试在运行时使用C#,Unity和this tutorial编译代码。我已经运行了所有东西,但是希望能够在伪代码中使用UnityEngine方法,例如Debug.Log();。为此,我在其中写入了using UnityEngine;,但出现以下错误:

找不到类型或名称空间名称“ UnityEngine”。您是否缺少程序集参考?

我该如何解决?

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

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

但是这给了我以下错误:

找不到元数据文件UnityEngine.dll。

这是我的代码中最相关的部分,但是您将无法像这样重现它。而是从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文件,并且不知道从何处开始修复该文件。我感谢您提供的任何帮助!

c# unity3d code-generation
1个回答
0
投票

您应该将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");
© www.soinside.com 2019 - 2024. All rights reserved.