using UnityEngine;
using System.Reflection;
using TNet;
using Mono.CSharp;
static class RuntimeCodeExample
{
static Assembly[] mCachedAssemblies = null;
static public object Execute (string code)
{
if (mCachedAssemblies == null)
{
mCachedAssemblies = System.AppDomain.CurrentDomain.GetAssemblies();
Mono
.CSharp.Evaluator.Init(new string[] { });
for (int i = 0, imax = mCachedAssemblies.Length; i < imax; ++i)
{
Assembly assembly = mCachedAssemblies[i];
if (assembly.FullName.Contains("Mono.")) continue;
if (assembly.FullName.Contains("UnityEditor")) continue;
if (assembly.FullName.Contains("Cecil")) continue;
try
{
Mono.CSharp.Evaluator.ReferenceAssembly(assembly);
}
catch (System.Exception ex)
{
Debug.LogError(assembly.FullName + "\n" + ex.Message);
return null;
}
}
}
System.Text.StringBuilder sb
= new System.Text.StringBuilder(""); sb.AppendLine("using System;");
sb.AppendLine("using UnityEngine;");
Mono.CSharp.Evaluator.Compile(sb.ToString());
if (string.IsNullOrEmpty(code)) return null;
if (code[code.Length - 1] != ';') code += ";";
object result = null;
bool result_set = false;
try
{
string s = Mono.CSharp.Evaluator.Evaluate("{\n" + code + "\n}", out result, out result_set);
if (!result_set && !string.IsNullOrEmpty(s)) Debug.LogError("Syntax error: " + s);
}
catch (System.Exception ex)
{
Debug.LogError(ex.Message);
}
return result_set ? result : null;
}
}