Skip to content

Instantly share code, notes, and snippets.

@kkestell
Created March 4, 2016 01:53
Show Gist options
  • Save kkestell/6f513ab8d7d662f418fc to your computer and use it in GitHub Desktop.
Save kkestell/6f513ab8d7d662f418fc to your computer and use it in GitHub Desktop.
using System;
using System.Reflection;
using System.CodeDom.Compiler;
using System.IO;
namespace LibZZT.ScriptingInterface
{
public interface IGameObjectScript
{
void Update();
}
}
namespace LibZZT
{
public class Script
{
private Assembly assembly;
private string code;
public Script(string filename)
{
Load(filename);
}
public string Code
{
get { return code; }
}
public void Load(string filename)
{
using (StreamReader sr = new StreamReader(filename))
{
code = sr.ReadToEnd();
}
Compile();
}
public void Compile()
{
Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();
CompilerParameters options = new CompilerParameters();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
CompilerResults result;
result = csProvider.CompileAssemblyFromSource(options, code);
if (result.Errors.HasErrors)
{
throw new Exception(String.Format("Script has errors.\n{0}", String.Join("\n", result.Errors)));
}
if (result.Errors.HasWarnings)
{
}
assembly = result.CompiledAssembly;
}
public void Run(GameObject gameObject)
{
if (assembly == null)
{
Compile();
}
foreach (Type type in assembly.GetExportedTypes())
{
foreach (Type iface in type.GetInterfaces())
{
if (iface == typeof(ScriptingInterface.IGameObjectScript))
{
Type[] types = { typeof(GameObject) };
ConstructorInfo constructor = type.GetConstructor(types);
if (constructor != null && constructor.IsPublic)
{
object[] constructorParams = { gameObject };
ScriptingInterface.IGameObjectScript scriptObject = constructor.Invoke(constructorParams) as ScriptingInterface.IGameObjectScript;
if (scriptObject != null)
{
scriptObject.Update();
}
else
{
throw new Exception("Script has errors");
}
}
else
{
throw new Exception("Script has no constructor");
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment