【Roslyn C#】Runtime环境Unity读取字符串代码

Roslyn C#

 

 

 

 

下载地址:https://files-cdn.cnblogs.com/files/sanyejun/RoslynC_RuntimeCompiler.zip

使用示例

using System.Collections;
using System.Collections.Generic;
using RoslynCSharp;
using UnityEngine;

public class Example : MonoBehaviour
{
    private ScriptDomain domain = null;
    //创建字符串代码
    private string source =
        "using UnityEngine;" +
        "class Test : MonoBehaviour" +
        "{" +
        " void SayHello()" +
        " {" +
        " Debug.Log(\"Hello World\");" +
        " }" +
        "}";

    
    // Start is called before the first frame update
    void Start()
    {
        // Create the domain - We are using C# code so we need the compiler
        domain = ScriptDomain.CreateDomain("MyTestDomain", true);
 
        // Compile and load the source code
        ScriptType type = domain. CompileAndLoadMainSource(source);

        // We need to pass a game object because 'Test' inherits from MonoBehaviour
        ScriptProxy proxy = type.CreateInstance(gameObject);
        
        // 调用字符串的 SayHello 方法
        proxy.Call("SayHello");
    }
    
}

 

posted @ 2021-06-18 12:29  三页菌  阅读(327)  评论(0编辑  收藏  举报