簡體   English   中英

在運行時編譯C#會引發一些錯誤

[英]Compiling c# at runtime throws some errors

我試圖統一地從字符串中編譯一些C#代碼,但是在運行代碼時出現此錯誤

我應該在控制台中發生什么情況,我應該看到每一幀都顯示“正在工作”,但是,一旦您啟動場景,就會立即彈出這兩個錯誤

錯誤1:

字符文字UnityEngine.Debug:Log(Object)WebSharp:Compile()中的字符過多(在Assets / Scripts / WebSharp.cs:54處)WebSharp:Start()(在Assets / Scripts / WebSharp.cs:17處)

錯誤2:

意外的符號'UnityEngine.Debug:Log(Object)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\\"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM