![](/img/trans.png)
[英]How to create and use same class in main C# code and runtime compiled code?
[英]How to use “UnityEngine” in runtime-compiled C# code?
我正在尝试使用 C#、Unity 和本教程在运行时编译代码。 我已经让一切都在运行,但希望能够使用 UnityEngine 方法,如Debug.Log();
在伪代码中。 为此,我using UnityEngine;
在其中,但收到以下错误:
找不到类型或命名空间名称“UnityEngine”。 您是否缺少程序集参考?
我该如何解决这个问题?
我尝试将 UnityEngine 的引用添加到CompilerParameters.ReferencedAssemblies
,如下所示:
//parameters is of type CompilerParameters
parameters.ReferencedAssemblies.Add("UnityEngine.dll");
但这给了我以下错误:
找不到元数据文件 UnityEngine.dll。
这是我的代码中最相关的部分,但您将无法像那样重现它。 相反,从上述教程中获取代码。
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 一起使用,因此我不知道 a.dll 文件是什么,并且在修复此问题时不知道从哪里开始。 我感谢任何形式的帮助!
您应该将 UnityEngine.dll 的路径放在那里,而不仅仅是UnityEngine.dll
,除非它存在于工作目录中,这是极不可能的。
根据这个答案,您可以在文件系统中轻松找到 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 例如,我有一个问题,我无法编译使用 Unity 屏幕 class 的 class,支持人员告诉我必须包含 UnityEngine.CoreModule.Z06416233FE5EC4C5933122E4AB248 资产的设置页面。
PS:我没有为这个推荐赚钱,我只是资产的快乐用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.