/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Compile and load code - Note that we use 'CompileAndLoadMainSource' which is the same as 'CompileAndLoadSource' but returns the main type in the compiled assembly ScriptType type = domain.CompileAndLoadMainSource(sourceCode, ScriptSecurityMode.UseSettings); // Create an instance of 'Example' ScriptProxy proxy = type.CreateInstance(); // Create an instance of 'Example' using the overload constructor proxy = type.CreateInstance(); // Call the method called 'ExampleMethod' and pass the string argument 'World' // Note that any exceptions thrown by the target method will not be caught proxy.Call("ExampleMethod", "World"); // Call the method called 'ExampleMethod' and pass the string argument 'Safe World' // Note that any exceptions thrown by the target method will handled as indicated by the 'Safe' name proxy.SafeCall("ExampleMethod", "Safe World"); }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Compile and load code - Note that we use 'CompileAndLoadMainSource' which is the same as 'CompileAndLoadSource' but returns the main type in the compiled assembly ScriptType type = domain.CompileAndLoadMainSource(sourceCode, ScriptSecurityMode.UseSettings); // Create an instance of 'Example' ScriptProxy proxy = type.CreateInstance(); // Create an instance of 'Example' using the overload constructor proxy = type.CreateInstance(); // Get the field value from a field with the name 'exampleField' and cast it to a string value string fieldString = (string)proxy.Fields["exampleField"]; // Check that the string we read has the expected value Debug.Log(fieldString == "Hello World"); // Set a field value with the name 'exampleField' // An exception may occur if the assigned type canot be implicitly converted to the actual field type proxy.Fields["exampleField"] = "Goodbye World"; // The safe version will handle any exceptions thrown when trying to access the field and return null if that is the case. fieldString = (string)proxy.SafeFields["exampleField"]; proxy.SafeFields["exampleField"] = fieldString; }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Compile and load code - Note that we use 'CompileAndLoadMainSource' which is the same as 'CompileAndLoadSource' but returns the main type in the compiled assembly ScriptType type = domain.CompileAndLoadMainSource(sourceCode, ScriptSecurityMode.UseSettings); // Create an instance of 'Example' ScriptProxy proxy = type.CreateInstance(); // Create an instance of 'Example' using the overload constructor proxy = type.CreateInstance(); // Get the property value from a property with the name 'ExampleProperty' and cast it to a string value string propertyString = (string)proxy.Properties["ExampleProperty"]; // Check that the string we read has the expected value Debug.Log(propertyString == "Hello World"); // Set a property value with the name 'ExampleProperty' // Note that this will throw an 'TargetException' because the specified property does not define a 'set' accessor proxy.Properties["ExampleProperty"] = "Goodbye World"; // The safe version will handle any exceptions thrown when trying to access the property and return null if that is the case. propertyString = (string)proxy.SafeProperties["ExampleProperty"]; proxy.SafeProperties["ExampleProperty"] = propertyString; }
public void ExecuteCode() { /*try * {*/ robotManagementCode = GetRobotManagementClass(); ScriptDomain domain = ScriptDomain.CreateDomain("MyDomain"); ScriptType type = domain.CompileAndLoadMainSource(robotManagementCode); ScriptProxy proxy = type.CreateInstance(robot); Tuple <bool, string> result = (Tuple <bool, string>)proxy.Call("isTaskCompleted"); if (result.Item1) { UI.ResultField.text = "<color=green>Задание выполнено!</color>"; Canvas.GetComponent <TaskCompletingActions>().MakeActions(taskNumber); UI.CloseTaskButton.transform.localScale = new Vector3(0, 0, 0); } else { UI.ResultField.text = "Есть ошибки. Попробуй ещё раз!"; } UI.OutputField.text = result.Item2; //} /*catch * { * Debug.Log("Exception!!!"); * UI.ResultField.text = "Есть ошибки. Попробуй ещё раз!"; * }*/ }
public void CreateObject(string abName, string prefabName, string scriptName, string layer, LuaFunction func = null, LuaFunction objCreatedCallback = null) { abName = abName + AppConst.ExtName; ResManager.LoadPrefab(abName, prefabName, delegate(UnityEngine.Object[] objs) { if (objs.Length == 0) { return; } // Get the asset. GameObject prefab = objs[0] as GameObject; if (prefab == null) { return; } GameObject go = Instantiate(prefab) as GameObject; go.layer = LayerMask.NameToLayer(layer); ScriptProxy scriptPorxy = go.AddComponent <ScriptProxy>(); scriptPorxy.className = scriptName; scriptPorxy.InitScript(); if (objCreatedCallback != null) { objCreatedCallback.Call(go); } if (func != null) { func.Call(go); } }); }
/// <summary> /// Resets the demo game and runs the tank with the specified C# code controlling it. /// </summary> /// <param name="source">The C# sorce code to run</param> public void RunTankScript(string source) { if (tankObject != null) { // Strip the old controller script TankController old = tankObject.GetComponent <TankController>(); if (old != null) { Destroy(old); } // Reposition the tank at its start position RespawnTank(); } // Compile the script ScriptType type = domain.CompileAndLoadScriptSource(source); if (type == null) { Debug.Log("Compile failed" + domain.GetErrorLineValue()); // Debug.LogError("Compile failed"); return; } else { GameObject.Find("ErrorExplain").GetComponent <Text>().text = ""; GameObject.Find("ErrorShowLine").GetComponent <Image>().color = new Color(0, 0, 0, 0f); } // Make sure the type inherits from 'TankController' if (type.IsSubtypeOf <TankController>() == true && tankObject != null) { // Attach the component to the object proxy = type.CreateInstance(tankObject); // Check for error if (proxy == null) { // Display error Debug.LogError(string.Format("Failed to create an instance of '{0}'", type.RawType)); return; } // Assign the bullet prefab to the 'TankController' instance proxy.Fields["playBuSprite"] = playBuSprite; proxy.Fields["buttonPlayimg"] = buttonPlayimg; proxy.Fields["bulletObject"] = bulletObject; proxy.Fields["nextStage"] = nextStage; // Call the run tank method crash //proxy.Fields["crash"] = crash; proxy.Call("RunTank"); } else { //if(tankObject != null){ // Debug.LogError("The script must inherit from 'TankController'"); //} } }
public static bool Exception(ScriptProxy proxy, Exception e) { if (OnScriptError != null) { OnScriptError(proxy, e); return(true); } return(false); }
/// <summary> /// Generates the ControlSpecific JavaScript. This script is safe to /// allow multiple callbacks to run simultaneously. /// </summary> private void GenerateControlSpecificJavaScript() { // Figure out the initial URL we're going to // Either it's the provided URL from the control or // we're posting back to the current page string Url = null; if (ServerUrl == null || ServerUrl == "") { Url = Context.Request.Path; } else { Url = ResolveUrl(ServerUrl); } //Uri ExistingUrl = Context.Request.Url; //// Must fix up URL into fully qualified URL for XmlHttp //if (!ServerUrl.ToLower().StartsWith("http")) // Url = ExistingUrl.Scheme + "://" + ExistingUrl.Authority + Url; string CallbackHandler = ClientCompleteHandler; if (string.IsNullOrEmpty(CallbackHandler)) { CallbackHandler = "null"; } string StartupCode = "function " + ClientID + @"_GetHoverPanel() { var hover = new HoverPanel(""#" + ClientID + @"""); hover.serverUrl = """ + Url + @"""; hover.timeout = " + Timeout.ToString() + @"; hover.completed = " + CallbackHandler + @"; hover.htmlTargetId = """ + (HtmlTargetClientId == "" ? ClientID : HtmlTargetClientId) + @"""; hover.postbackMode = """ + PostBackMode.ToString() + @"""; hover.navigateDelay = " + NavigateDelay.ToString() + @"; hover.adjustWindowPosition = " + AdjustWindowPosition.ToString().ToLower() + @"; hover.eventHandlerMode = """ + EventHandlerMode.ToString() + @"""; hover.shadowOpacity = " + ShadowOpacity.ToString(CultureInfo.InvariantCulture.NumberFormat) + @"; hover.shadowOffset = " + ShadowOffset + @"; hover.hoverOffsetRight = " + HoverOffsetRight.ToString() + @"; hover.hoverOffsetBottom = " + HoverOffsetBottom.ToString() + @"; return hover; } $( function() { window." + ClientID + " = " + ClientID + @"_GetHoverPanel(); }); "; ScriptProxy.RegisterStartupScript(this, GetType(), ClientID + "_STARTUP", StartupCode, true); }
/// <summary> /// Resets the demo game and runs the tank with the specified C# code controlling it. /// </summary> /// <param name="source">The C# sorce code to run</param> public IEnumerator RunTankScript(string source) { // Strip the old controller script TankController old = tankObject.GetComponent <TankController>(); if (old != null) { Destroy(old); } // Reposition the tank at its start position RespawnTank(); // Compile the script asynchronously AsyncCompileLoadOperation task = domain.CompileAndLoadScriptSourcesAsync(source); // Wait for compile to complete yield return(task); if (task.IsSuccessful == false) { Debug.LogError("Compile failed"); yield break; } // Get the main compiled type ScriptType type = task.MainType; // Make sure the type inherits from 'TankController' if (type.IsSubtypeOf <TankController>() == true) { // Attach the component to the object ScriptProxy proxy = type.CreateInstance(tankObject); // Check for error if (proxy == null) { // Display error Debug.LogError(string.Format("Failed to create an instance of '{0}'", type.RawType)); yield break; } // Assign the bullet prefab to the 'TankController' instance proxy.Fields["bulletObject"] = bulletObject; // Call the run tank method proxy.Call("RunTank"); } else { Debug.LogError("The script must inherit from 'TankController'"); } }
/// <summary> /// Causes the mouse crawler to stop moving and reset to its initial position. /// </summary> public void StopCrawler() { if (activeCrawlerScript != null) { // Get the maze crawler instance MazeCrawler mazeCrawler = activeCrawlerScript.GetInstanceAs <MazeCrawler>(false); // Call the restart method mazeCrawler.Restart(); // Destroy script activeCrawlerScript.Dispose(); activeCrawlerScript = null; } }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (Closable) { string script = "\r\n$( function() { $('#" + DragHandleID + "').find('img').click( function(e) { " + ClientID + ".hide(); } );})\r\n"; ScriptProxy.RegisterStartupScript(this, typeof(ControlResources), ID + "_ModalCloseHandler", script, true); } if (!string.IsNullOrEmpty(ShowScript)) { ScriptProxy.RegisterStartupScript(this, typeof(ControlResources), ID + "_ModalShow", ShowScript, true); } }
public MainViewModel(object script) { _scriptProxy = new ScriptProxy(script); _settingsRepo = new SettingsRepository(); OpenPatientContextCommand = new RelayCommand(OpenPatientContext); RemovePatientContextCommand = new RelayCommand(RemovePatientContext); RemoveAllPatientContextsCommand = new RelayCommand(RemoveAllPatientContexts); RunWithPatientContextCommand = new RelayCommand(RunWithPatientContext); OpenPatientCommand = new RelayCommand(OpenPatient); RunScriptCommand = new RelayCommand(RunScript); ExitCommand = new RelayCommand(Exit); LoadSettings(); }
protected override void OnLoad(EventArgs e) { if (Visible) { StringBuilder script = new StringBuilder(); script.Append("'#" + ClientID + "',{"); if (!string.IsNullOrEmpty(HeaderId)) { script.Append("headerId: '" + HeaderId + "',"); } if (!string.IsNullOrEmpty(ContentId)) { script.Append("contentId: '" + ContentId + "',"); } if (!string.IsNullOrEmpty(ClientDialogHandler)) { script.Append("dialogHandler:" + ClientDialogHandler + ","); // Clear out the handler so the dragpanel doesn't implement it ClientDialogHandler = null; } if (FadeinBackground) { script.Append("fadeInBackground: true,"); } if (!string.IsNullOrEmpty(OverlayId)) { script.Append("overlayId: '" + OverlayId + "',"); } script.Append("backgroundOpacity:" + BackgroundOpacity.ToString(CultureInfo.InvariantCulture) + ","); string scrpt = "var " + ID + " = new _ModalDialog(" + script.ToString().TrimEnd(',') + "});\r\n"; ScriptProxy.RegisterStartupScript(this, typeof(ControlResources), ID + "_ModalStart", scrpt, true); } base.OnLoad(e); }
/// <summary> /// Resets the demo game and runs the tank with the specified C# code controlling it. /// </summary> /// <param name="source">The C# sorce code to run</param> public void RunTankScript(string source) { // Strip the old controller script TankController old = tankObject.GetComponent <TankController>(); if (old != null) { Destroy(old); } // Reposition the tank at its start position RespawnTank(); // Compile the script ScriptType type = domain.CompileAndLoadScriptSource(source); if (type == null) { Debug.LogError("Compile failed"); return; } // Make sure the type inherits from 'TankController' if (type.IsSubtypeOf <TankController>() == true) { // Attach the component to the object ScriptProxy proxy = type.CreateInstance(tankObject); // Check for error if (proxy == null) { // Display error Debug.LogError(string.Format("Failed to create an instance of '{0}'", type.RawType)); return; } // Assign the bullet prefab to the 'TankController' instance proxy.Fields["bulletObject"] = bulletObject; // Call the run tank method proxy.Call("RunTank"); } else { Debug.LogError("The script must inherit from 'TankController'"); } }
public new ObjectGuid AddObject(object obj, bool postLoad, ObjectGuid objectId) { if (obj is IScriptLogic) { ScriptProxy proxy = new ScriptProxy(); if (!proxy.SetLogic((IScriptLogic)obj, postLoad)) { return(Sims3.SimIFace.Simulator.kBadObjectGuid); } Simulator_AddObjectImpl(proxy, objectId.Value); return(ExceptionTrap.ProcessObjectGuid(proxy.ObjectId, true)); } ITask task = (ITask)obj; Simulator_AddObjectImpl(task, objectId.Value); return(ExceptionTrap.ProcessObjectGuid(task.ObjectId, true)); }
public IEnumerator RunAsync(string source, TextMeshProUGUI textUI, List <int> list, List <double> listD) { LoadingCircle.UpdateLoad(true); Debug.Log(source); ScriptDomain domain = ScriptDomain.CreateDomain("resposta"); AsyncCompileOperation compileRequest = domain.CompileAndLoadSourceAsync(source, ScriptSecurityMode.UseSettings); // Wait for operation to complete yield return(compileRequest); // Check for compiler errors if (compileRequest.IsSuccessful == false) { // Get all errors foreach (CompilationError error in compileRequest.CompileDomain.CompileResult.Errors) { if (error.IsError == true) { Debug.LogError(error.ToString()); textUI.text = error.ToString(); } else if (error.IsWarning == true) { Debug.LogWarning(error.ToString()); } } } else { type = compileRequest.CompiledType; proxy = type.CreateInstance(this.gameObject); proxy.Fields["_inputs"] = list; proxy.Fields["_Dinputs"] = listD; proxy.Call(initBlock.name); if ((string)proxy.Fields["_loopError"] != null) { textUI.text = (string)proxy.Fields["_loopError"]; } else { textUI.text = (string)proxy.Fields["_output"]; } } LoadingCircle.UpdateLoad(false); }
void Start() { // Should we enable the compiler for our domain // This is requried if we want to load C# scripts as opposed to assemblies bool initCompiler = true; // Create our domain domain = ScriptDomain.CreateDomain("ModDomain", initCompiler); // Load the source code into our domain ScriptType type = domain.CompileAndLoadScriptSource(sourceCode); // Create an instance of our type ScriptProxy proxy = type.CreateInstance(); // Call the test method proxy.Call("TestMethod"); }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Compile and load code - Note that we use 'CompileAndLoadMainSource' which is the same as 'CompileAndLoadSource' but returns the main type in the compiled assembly ScriptAssembly assembly = domain.CompileAndLoadSource(sourceCode, ScriptSecurityMode.UseSettings); // Find all types ScriptType type = assembly.FindType("Example"); ScriptType behaviourType = assembly.FindSubTypeOf <MonoBehaviour>("ExampleBehaviour"); ScriptType scriptableType = assembly.FindSubTypeOf <ScriptableObject>("ExampleScriptable"); // Create an instance of 'Example' ScriptProxy proxy = type.CreateInstance(); // Create an instance of 'Example' using the overload constructor proxy = type.CreateInstance(null, "Hello World"); // Create an instance of 'ExampleBehaviour' // Note that we need to pass a game object to attach the component to because it inherits from 'MonoBehaviour' // Failing to provide a valid game object will case the result to be null // Awake, OnEnable, Start and other Unity callbacks will be triggered as you would expect ScriptProxy behaviourProxy = behaviourType.CreateInstance(gameObject); // Both outputs will be 'true' Debug.Log(behaviourProxy.IsMonoBehaviour); Debug.Log(behaviourProxy.IsUnityObject); // Create an instance of 'ExampleScriptable' // this is much the same as creating a normal instance however it will be constructed using 'ScriptableObject.CreateInstance' because it inherits from 'ScriptableObject' ScriptProxy scriptableProxy = scriptableType.CreateInstance(); // Both outputs will be 'true' Debug.Log(scriptableType.IsScriptableObject); Debug.Log(scriptableType.IsUnityObject); }
/// <summary> /// Causes the mouse crawler to reset its initial position and start crawling again. /// </summary> public void RestartCrawler() { if (activeCrawlerScript != null) { ScriptType type = activeCrawlerScript.ScriptType; // Get the maze crawler instance MazeCrawler mazeCrawler = activeCrawlerScript.GetInstanceAs <MazeCrawler>(false); // Call the restart method mazeCrawler.Restart(); // Remove and re-add script to reset it activeCrawlerScript.Dispose(); activeCrawlerScript = type.CreateInstance(mazeMouse); activeCrawlerScript.Fields["breadcrumbPrefab"] = breadcrumbPrefab; activeCrawlerScript.Fields["moveSpeed"] = mouseSpeed; } }
/// <summary> /// This method just builds the various JavaScript blocks as strings /// and assigns them to the ClientScript object. // /// MouseEvents to the panel to show/hide the panel on mouse out /// operations. /// </summary> /// <param name="e"></param> protected override void OnPreRender(EventArgs e) { if (!IsCallback) { GenerateControlSpecificJavaScript(); // On HoverPanel operation we need to hide the window when we move off if (EventHandlerMode == HoverEventHandlerModes.ShowHtmlAtMousePosition) { if (AutoCloseHoverWindow) { // Register hover out/in behavior on startup ScriptProxy.RegisterStartupScript(this, typeof(ControlResources), ClientID + "_hpStartup", @"$( function() { $('#" + ClientID + @"') .hover( function() { " + ClientID + @".show(); }, function() { " + ClientID + @".hide(); } ); }); ", true); } } else if (EventHandlerMode == HoverEventHandlerModes.ShowIFrameAtMousePosition || EventHandlerMode == HoverEventHandlerModes.ShowIFrameInPanel) { LiteralControl Ctl = new LiteralControl(); Ctl.Text = "<iframe id='" + ClientID + "_IFrame' frameborder='0' width='" + Width.ToString() + "' height='" + IFrameHeight.ToString() + "'></iframe>"; Controls.Add(Ctl); } if (PanelOpacity != 1) { ScriptProxy.RegisterStartupScript(this, typeof(ControlResources), ClientID + "_hpOpacity", @"$( function() { $('#" + ClientID + @"').css('opacity'," + PanelOpacity.ToString(CultureInfo.InvariantCulture.NumberFormat) + @"'); }); ", true); } } base.OnPreRender(e); }
void Start() { // Should we enable the compiler for our domain // This is required if we want to load C# scripts as opposed to assemblies. bool initCompiler = true; // Create our domain domain = ScriptDomain.CreateDomain("ModDomain", initCompiler); // Load the source code into our domain ScriptType type = domain.CompileAndLoadScriptSource(sourceCode); // Create an instance of our type - We need to pass a game object because 'Test' inherits from monobehaviour ScriptProxy proxy = type.CreateInstance(gameObject); // Coroutines are supported by default (true) but support can be disabled by specifying 'false' as the value. // Any method that returns 'IEnumerator' will be called as a coroutine. proxy.supportCoroutines = true; // Call the test method as a coroutine proxy.Call("TestMethod"); }
public bool UpdateScript(Ship ship, StarSystem starSystem, string code) { if (domain != null) { domain.Dispose(); } domain = ScriptDomain.CreateDomain("ShipDomain", true); //domain.RoslynCompilerService.ReferenceAssemblies.Add(typeof(UnityEngine.Object).Assembly); //domain.RoslynCompilerService.ReferenceAssemblies.Add(typeof(Ship).Assembly); //domain.RoslynCompilerService.ReferenceAssemblies.Add(typeof(StarSystem).Assembly); //domain.RoslynCompilerService.ReferenceAssemblies.Add(typeof(LandableObject).Assembly); type = domain.CompileAndLoadMainSource(@code); if (proxy != null && !proxy.IsDisposed) { Debug.Log(proxy.IsDisposed); proxy.Dispose(); } Debug.Log(gameObject.name); Debug.Log(type.Name); proxy = type.CreateInstance(gameObject); Debug.Log(gameObject.name); if (type != null) { proxy.Fields["ship"] = ship; proxy.Fields["starSystem"] = starSystem; return(true); } else { return(false); } }
void Start() { // Should we enable the compiler for our domain // This is requried if we want to load C# scripts as opposed to assemblies bool initCompiler = true; // Create our domain domain = ScriptDomain.CreateDomain("ModDomain", initCompiler); // Load the source code into our domain ScriptType type = domain.CompileAndLoadScriptSource(sourceCode); // Create an instance of our type ScriptProxy proxy = type.CreateInstance(); // We know that the 'Test' class implements the 'IExampleInterface' so we can access the implementation like this: IExampleInterface instance = proxy.GetInstanceAs <IExampleInterface>(true); // Call the hello method on the instance instance.SayHello(); // Call the goodbye method in the instance instance.SayGoodbye(); }
/// <summary> /// Main run method. /// This causes any modified code to be recompiled and executed on the mouse crawler. /// </summary> public void RunCrawler() { // Get the C# code from the input field string cSharpSource = runCrawlerInput.text; // Dont recompile the same code if (activeCSharpSource != cSharpSource || activeCrawlerScript == null) { // Remove any other scripts StopCrawler(); try { // Compile code ScriptType type = domain.CompileAndLoadMainSource(cSharpSource, ScriptSecurityMode.UseSettings, assemblyReferences); // Check for null if (type == null) { if (domain.RoslynCompilerService.LastCompileResult.Success == false) { throw new Exception("Maze crawler code contained errors. Please fix and try again"); } else if (domain.SecurityResult.IsSecurityVerified == false) { throw new Exception("Maze crawler code failed code security verification"); } else { throw new Exception("Maze crawler code does not define a class. You must include one class definition of any name that inherits from 'RoslynCSharp.Example.MazeCrawler'"); } } // Check for base class if (type.IsSubTypeOf <MazeCrawler>() == false) { throw new Exception("Maze crawler code must define a single type that inherits from 'RoslynCSharp.Example.MazeCrawler'"); } // Create an instance activeCrawlerScript = type.CreateInstance(mazeMouse); activeCSharpSource = cSharpSource; // Set speed value activeCrawlerScript.Fields["breadcrumbPrefab"] = breadcrumbPrefab; activeCrawlerScript.Fields["moveSpeed"] = mouseSpeed; } catch (Exception e) { // Show the code editor window codeEditorWindow.SetActive(true); throw e; } } else { // Get the maze crawler instance MazeCrawler mazeCrawler = activeCrawlerScript.GetInstanceAs <MazeCrawler>(false); // Call the restart method mazeCrawler.Restart(); } }