我试图从一个字符串中编译一些c#代码然而我在运行代码时遇到这个错误
应该在控制台中发生什么,我应该看到"工作"打印每一帧,但一旦你启动场景,这两个错误立即弹出
错误1:
字符文字中的字符过多 UnityEngine.Debug:日志(对象) WebSharp:Compile()(在Assets / Scripts / WebSharp.cs:54) WebSharp:Start()(在Assets / Scripts / WebSharp.cs:17)
错误2:
意外的符号' UnityEngine.Debug:日志(对象) WebSharp:Compile()(在Assets / Scripts / WebSharp.cs:54) WebSharp:Start()(在Assets / Scripts / WebSharp.cs:17)
完整的班级代码
using System;
using System.Reflection;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Microsoft.CSharp;
public class WebSharp : MonoBehaviour {
protected Assembly generatedAssembly;
private Type myScriptType = null;
private object myScriptInstance = null;
private void Start(){
Compile ();
}
private string scriptText = "" +
"using UnityEngine; " +
"public class TestScript: MonoBehavior{" +
"private void Update(){" +
"Debug.Log('Working');" +
"}" +
"}";
private void Update(){
if (myScriptType == null || myScriptInstance == null) {
return;
}
//Run the scripts update function
myScriptType.InvokeMember ("Update", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, myScriptInstance, null);
}
private void Compile(){
try{
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters compilerParams = new CompilerParameters();
compilerParams.CompilerOptions = "/target:library /optimize /warn:0";
compilerParams.GenerateExecutable = false;
compilerParams.GenerateInMemory = true;
compilerParams.IncludeDebugInformation = false;
compilerParams.ReferencedAssemblies.Add("System.dll");
compilerParams.ReferencedAssemblies.Add("System.Core.dll");
CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParams,scriptText);
if(results.Errors.Count > 0){
foreach(CompilerError error in results.Errors){
Debug.Log(error.ErrorText);
}
}else{
generatedAssembly = results.CompiledAssembly;
if(generatedAssembly != null){
myScriptType = generatedAssembly.GetType("TestScript");
myScriptInstance = Activator.CreateInstance(myScriptType);
Debug.LogAssertion("Success");
}
}
}catch(Exception e){
Debug.LogError (e.Message);
}
}
}
答案 0 :(得分:0)
'Working'
在scripttext
中不是有效的字符串。字符串文字需要双引号。使用\转义双引号,例如\"Working\"