//Remember, you can't compile MonoBehaviours with CSSCriptEngineRemote, stick to //plain C# classes for safety void RemoteCompileType() { CSScriptEngineRemote engineRemote = new CSScriptEngineRemote(); engineRemote.LoadDomain();//Important! engineRemote.AddUsings("using UnityEngine;"); string typeCode = @" public class SimpleType { public void PrintHey() { Debug.Log(""Hey!""); } } "; engineRemote.CompileType("SimpleType", typeCode); engineRemote.CompileCode(@" SimpleType sm = new SimpleType();sm.PrintHey(); "); engineRemote.ExecuteLastCompiledCode(); engineRemote.UnloadDomain();//Important! }
void Update() { if (Remote) { if (_engineRemote.RemoteDomain == null) { _engineRemote.LoadDomain("RemoteDomain"); _engineRemote.AddUsings("using WhitelistAPI;"); _engineRemote.AddUsings("using UnityEngine;"); _engineRemote.AddUsings("using System;"); } if (!GameObjectWatcher.Initialized) { GameObjectWatcher.Initialize(); } } else if (_engineRemote.RemoteDomain != null) { GameObjectWatcher.DestroyAllDynamicGOs(); if (!ResetSceneOnExecute) { GameObjectWatcher.Disable(); } _engineRemote.UnloadDomain(); } if (ResetSceneOnExecute) { if (!GameObjectWatcher.Initialized) { GameObjectWatcher.Initialize(); } } else { if (GameObjectWatcher.Initialized) { GameObjectWatcher.Disable(); } } }
void CompileCodeTest() { //Setup string code = @" GameObject gob = new GameObject(""DynamicallyCreatedGO""); "; _engine.AddUsings("using UnityEngine;"); //Action _engine.CompileCode(code); _engine.ExecuteLastCompiledCode(); //Assert GameObject go = GameObject.Find("DynamicallyCreatedGO"); Assert.IsTrue(go != null); //TearDown Destroy(go); }
//With CSScriptEngineRemote you must always invoke LoadDomain before using it, //and always invoke Unloaddomain or Dispose when you're done using it void RemoteCompileCode() { //Let's check that no dynamic assemblies were loaded in main appDomain Debug.Log("Assemblies currently loaded in main appdomain: " + AppDomain.CurrentDomain.GetAssemblies().Length); //You can ensure dispose call by utilizing using block, for example using (CSScriptEngineRemote engineRemote = new CSScriptEngineRemote()) { engineRemote.LoadDomain(); engineRemote.AddUsings("using UnityEngine;"); engineRemote.CompileCode(@"Debug.Log(""Hey!"");"); engineRemote.ExecuteLastCompiledCode(); } Debug.Log("Assemblies currently loaded in main appdomain: " + AppDomain.CurrentDomain.GetAssemblies().Length); }