简体   繁体   中英

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

I am trying to compile code at runtime using C#, Unity and this tutorial . I've got everything running, but want to be able to use UnityEngine methods like Debug.Log(); in the pseudo-code. In order to do so, I wrote using UnityEngine; in it, but got the following error:

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

How do I solve this?

I have tried adding a reference of UnityEngine to CompilerParameters.ReferencedAssemblies like this:

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

but that gives me the following error:

Metadata file UnityEngine.dll could not be found.

This is the most relevant part of my code, but you won't be able to reproduce it like that. Instead, get the code from the above mentioned tutorial.

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");
}

Since I am inexperienced with C#, and only use it with Unity, I don't know what a.dll file is and am clueless about where to start when fixing this. I am thankful for any kind of help!

You are supposed to put the path of the UnityEngine.dll there, not just UnityEngine.dll , unless it exists in the working directory, which is highly unlikely.

According to this answer , you can easily find UnityEngine.dll (and other dlls as well) in your file system. It is under Editor\Data\Managed , so you should write:

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

I tried some of the open source solutions, but couldn't find a solution which worked on all 3 platforms. Finally I bought this asset, which works without problems on Windows, Mac and Linux: https://assetstore.unity.com/packages/tools/integration/dynamic-c-82084 The documentation and support is very good. For example I had a problem that I couldn't compile a class which uses the Unity Screen class, and the support told me that I had to include the UnityEngine.CoreModule.dll in the settings page of the asset, which solved the problem.

PS: I don't get money for this recommendation, I'm just a happy user of the asset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM