# How do I compile a C# script at runtime and attach it as a component to a game object

The idea here is to let users program the behaviour of an agent in a way that reminds of the "Screeps" game, where you get to develop code which later runs and dictates the behaviour of your units.

My idea is to let users develop the behaviour or their units with C# code, compile that code at runtime and attach it as a MonoBehavior to an existing game object.

How can I achieve this?

• You could also use an existing scripting language. For example, there is JavaScript.net which allows you to interpret and execute JavaScripts from a C# program. Pro: minimal implementation effort, you can refer users to existing JS learning material. Con: Might be too powerful and too confusing for your limited use-case. Sep 21 '16 at 10:45
• Another option would be to create a visual editor where users drag and drop around blocks of instructions. Pro: Looks and feels more like a game, easier to teach, easier to learn for non-programmers. Contra: Takes time to develop, might be too limiting for experienced programmers (and those who become it by playing the game). Sep 21 '16 at 10:51
• One of my ideas where precisely instruction blocks which has its pros and cons, allowing users to create their own blocks would have the benefit from both ideas @Philipp provided, am I right or I am missing something making that statement? Sep 21 '16 at 11:06
• "How to achieve this" is an extremely broad question. There are several independent aspects to this, like designing the UI, deciding what blocks you need, how to represent them as data-structures and how to interpret these data-structures. You need to specify which of these aspects you have a problem with and what that problem is. Sep 21 '16 at 11:11
• Sep 21 '16 at 11:57

I haven't done this myself, so this answer is based on an article by exodrifter (I just Googled "unity runtime compile" and found 4 answers right at the top, so don't neglect to try searching yourself!)

What you're describing is possible, but not without pitfalls:

• Use .Net 2.0 compatibility level, otherwise some namespaces you need may be absent.

• Not every platform will allow you to compile new C# from strings at runtime - specifically Android and iOS disallow this.

• Out of the box this works on Windows, but not on Macs/Linux unless the user has the Mono SDK installed. You can include aeroson's mcs-ICodeCompiler to build this functionality into your game as a plugin.

## exodrifter's example code (modified to add a component)

(refer to the article for full details - I just want to include enough here that this answer is a useful signpost even if the linked article goes down)

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
using UnityEngine;

public class RuntimeCompileTest : MonoBehaviour
{
void Start()
{
var assembly = Compile(@"
using UnityEngine;

public class RuntimeCompiled : MonoBehaviour
{
{
}

void Start()
{
Debug.Log(""The runtime compiled component was successfully attached to"" + gameObject.name);
}
}");

var runtimeType = assembly.GetType("RuntimeCompiled");
var del = (Func<GameObject, MonoBehaviour>)
Delegate.CreateDelegate(
typeof(Func<GameObject, MonoBehaviour>),
method
);

// We ask the compiled method to add its component to this.gameObject

// The delegate pre-bakes the reflection, so repeated calls don't
// cost us every time, as long as we keep re-using the delegate.
}

public static Assembly Compile(string source)
{
// Replace this Compiler.CSharpCodeProvider wth aeroson's version
// if you're targeting non-Windows platforms:
var provider = new CSharpCodeProvider();
var param = new CompilerParameters();

// Add ALL of the assembly references
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
}

// Or, uncomment just the assemblies you need...

// System namespace for common types like collections.

// This contains methods from the Unity namespaces:

// This assembly contains runtime C# code from your Assets folders:
// (If you're using editor scripts, they may be in another assembly)

// 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}\n",
error.ErrorNumber, error.ErrorText);
}
throw new Exception(msg.ToString());
}

// Return the assembly
return result.CompiledAssembly;
}
}


## Warning

Be very careful when letting your game compile & run scripts you didn't write yourself. These scripts could be made to do just about anything the player's user account has privilege to do - delete or corrupt user files, download and run malware, snoop personal information, all of that.

As much as we might try to block & detect these cases, I'd never be especially confident we'd caught them all - there's always the possibility some C# language feature I didn't know about lets them access features I thought were cut off.

If the script is only created by the local player, then they can break the game in arbitrary ways, but can't do anything to their computer they lacked permission to do anyway. But if players can share scripts, download them from a network resource, or can be tricked into copying-and-pasting a script they didn't write, then this becomes an attack vector that can be exploited.

If you want to allow programming by the player without opening up this kind of vulnerability, consider writing your own virtual machine to parse/interpret/execute the player's scripts in a more limited environment that you control completely.

• Thanks for the input, especially regarding the warnings you gave me, I had an idea of them but not so concise as you stated Sep 28 '16 at 10:31