Hi im a trying to compile scripts and attach them to objects at runtime and make them communicate each other.
I am using .NET 2.0 and the code i found here from exodrifter on the forums to achive the compilation and use reflection on the compiled object to attach itself to an object
the code i use to achive that is pasted below
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
using UnityEngine;
public class CompilerExample : MonoBehaviour
{
void Start()
{
var assembly = Compile(@"
using UnityEngine;
public class Test
{
public static void Foo()
{
Debug.Log(""Hello, World!"");
}
}");
var method = assembly.GetType("Test").GetMethod("Foo");
var del = (Action)Delegate.CreateDelegate(typeof(Action), method);
del.Invoke();
}
public static Assembly Compile(string source)
{
var provider = new CSharpCodeProvider();
var param = new CompilerParameters();
// Add ALL of the assembly references
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
param.ReferencedAssemblies.Add(assembly.Location);
}
// Add specific assembly references
//param.ReferencedAssemblies.Add("System.dll");
//param.ReferencedAssemblies.Add("CSharp.dll");
//param.ReferencedAssemblies.Add("UnityEngines.dll");
// Generate a dll in memory
param.GenerateExecutable = false;
param.GenerateInMemory = true;
// Compile the source
var result = provider.CompileAssemblyFromSource(param, source);
if (result.Errors.Count > 0) {
var msg = new StringBuilder();
foreach (CompilerError error in result.Errors) {
msg.AppendFormat("Error ({0}): {1}
",
error.ErrorNumber, error.ErrorText);
}
throw new Exception(msg.ToString());
}
// Return the assembly
return result.CompiledAssembly;
}
}
The problem is this method only works with unitys built in funtions and variables such as transform.Rotate when i try to attach a runtime script like this to an object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Scream : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//tellName();
}
public void tellName() {
Debug.Log("I am the " + transform.gameObject.name);
}
}
and this to another object at runtime
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Caller : MonoBehaviour {
GameObject go;
Scream sc;
// Use this for initialization
void Start () {
go = GameObject.Find("GreenCube");
sc = (Scream)go.GetComponent(typeof(Scream)) as Scream;
}
// Update is called once per frame
void Update () {
sc.tellName();
}
}
I cannot manage to call the function from the runtimeAdded scripts because unity doesnt realise that the runtime created script has the declared method and throws namespace or type cannot be found error.
Hope i can make my promlem clear. Is there a way to achive this or am i out of luck.