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