我正在我的Unity游戏中的运行时编译代码,并希望在该用户生成的代码中使用预制的类。尽管两个类都在同一个命名空间中,但是在运行时编译的类找不到另一个,并给了我以下错误:
InvalidOperationException:错误(CS0234):类型或名称空间名称'PremadeClass'(即类名称)在名称空间'GameLevel'(即名称空间名称)中不存在。您是否缺少程序集参考?
基于我之前在该项目中遇到的错误,我想我需要在运行时代码中引用预制类的.dll
文件,但不知道Unity将每个类的代码存储在哪里,或者它甚至生成它们。但是,这可能是错误的,因为两个类都在同一个名称空间中,并且我对C#经验不足。
我使用this tutorial编写了编译代码-对其进行检查以获取更多信息(这只是带有一些说明的纯代码,但这是最重要的部分:
public void Compile() {
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
//...
parameters.ReferencedAssemblies.Add("path/UnityEngine.dll");
parameters.OutputAssembly = "path/fileName.dll";
parameters.GenerateInMemory = false; //generates actual file
parameters.GenerateExecutable = false; //generates .dll instead of .exe
//...
parameters.OutputAssembly = Application.dataPath + className + ".dll";
CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
//...
Assembly assembly = results.CompiledAssembly;
Type program = assembly.GetType("GameLevel." + className);
MethodInfo excecuteMethod = program.GetMethod("Excecute");
excecuteMethod.Invoke(null, null);
}
这是预制类的基本结构:
namespace GameLevel
{
public class PrecompiledClass
{
public void Foo() {
}
}
}
这基本上是运行时代码如何利用它:
namespace GameLevel
{
public class RuntimeClass
{
public void Foo() {
new PrecompiledClass().Foo();
}
}
}
感谢您的回答!
将预制的类放在单独的程序集(dll)中,然后将该dll包含在parameters.ReferencedAssemblies.Add("path/Premade.dll")
中
之所以使用单独的程序集,是因为只有您希望玩家访问的类才对他们可见。