/// <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");
        }
예제 #2
0
        /// <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;
        }
예제 #4
0
 /// <summary>
 /// Gets the default value for the given type (can be value type or reference type).
 /// </summary>
 /// <param name="type">The type.</param>
 /// <returns>The created instance.</returns>
 public static object GetDefaultValue(ScriptType type)
 {
     if (type.Type == typeof(string))
     {
         return(string.Empty);
     }
     if (type.Type == typeof(Color))
     {
         return(Color.White);
     }
     if (type.Type == typeof(Quaternion))
     {
         return(Quaternion.Identity);
     }
     if (type.Type == typeof(Transform))
     {
         return(Transform.Identity);
     }
     if (type.Type == typeof(Matrix))
     {
         return(Matrix.Identity);
     }
     if (type.Type == typeof(BoundingBox))
     {
         return(BoundingBox.Zero);
     }
     if (type.Type == typeof(Rectangle))
     {
         return(Rectangle.Empty);
     }
     if (type.Type == typeof(ChannelMask))
     {
         return(ChannelMask.Red);
     }
     if (type.Type == typeof(MaterialSceneTextures))
     {
         return(MaterialSceneTextures.BaseColor);
     }
     if (type.IsValueType)
     {
         var value = type.CreateInstance();
         Utilities.Utils.InitDefaultValues(value);
         return(value);
     }
     if (ScriptType.Object.IsAssignableFrom(type))
     {
         return(null);
     }
     if (type.CanCreateInstance)
     {
         var value = type.CreateInstance();
         Utilities.Utils.InitDefaultValues(value);
         return(value);
     }
     throw new NotSupportedException("Cannot create default value for type " + type);
 }
예제 #5
0
    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 = "Есть ошибки. Попробуй ещё раз!";
         * }*/
    }
예제 #6
0
        /// <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'");
                //}
            }
        }
예제 #7
0
        /// <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);
        }
예제 #8
0
        private void Spawn(ScriptType item, SceneGraphNode hit, ref Vector3 hitLocation)
        {
            var actor = item.CreateInstance() as Actor;

            if (actor == null)
            {
                Editor.LogWarning("Failed to spawn actor of type " + item.TypeName);
                return;
            }
            actor.Name = item.Name;
            Spawn(actor, ref hitLocation);
        }
예제 #9
0
        /// <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>
        /// 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'");
            }
        }
예제 #11
0
    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);
    }
예제 #12
0
        /// <summary>
        /// Tries to create object instance of the given full typename. Searches in-build Flax Engine/Editor assemblies and game assemblies.
        /// </summary>
        /// <param name="typeName">The full name of the type.</param>
        /// <returns>The created object or null if failed.</returns>
        public static object CreateInstance(string typeName)
        {
            object     obj  = null;
            ScriptType type = GetType(typeName);

            if (type && type.CanCreateInstance)
            {
                try
                {
                    return(obj = type.CreateInstance());
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                }
            }
            return(obj);
        }
예제 #13
0
        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");
        }
예제 #14
0
        /// <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;
            }
        }
예제 #15
0
    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);
        }
    }
예제 #16
0
        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");
        }
        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();
        }
예제 #18
0
        /// <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();
            }
        }