![](/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.