【问题标题】:Compiling c# at runtime throws some errors在运行时编译 c# 会引发一些错误
【发布时间】:2026-01-25 00:40:02
【问题描述】:

我正在尝试从一个字符串中统一编译一些 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);
        }
    }
}

【问题讨论】:

  • 'Working' 不是scripttext 中的有效字符串。字符串文字需要双引号。使用 \ 转义双引号,例如\"Working\"
  • 成功了!谢谢

标签: c# unity3d compiler-errors monodevelop


【解决方案1】:

'Working' 不是scripttext 中的有效字符串。字符串文字需要双引号。使用 \ 转义双引号,例如\"Working\"

【讨论】: