Load a .cs file at runtime
Hi Unity Answers members,
I appreciate the below may be tricky to accomplish but I would be really grateful for any help that anyone can provide.
I am trying to set up a method of loading mod files into my code and running the relevant information. For example, I have an interface set up a below;
public interface IMod {
void register ( );
}
I would like to be able to create a file, for example, "MyMod.cs" and place this in the relevant 'mods' folder. This file would contain the below code;
public class MyMod : IMod {
public void register ( ) {
Debug.Log ( "Just testing the code" );
}
}
In my 'main' MonoBehaviour script, in the Start method, I would like to be able to do something like the below;
foreach ( string file in Directory.GetFiles ( "mods", "*.cs" ) {
IMod mod = parseFileToIMod ( file );
mod.register ( );
}
Does anybody know of a (relatively) simple way to do this? I've been searching for the best part of an afternoon now and the closest I got was CSScript, but, due to Unity's .NET versioning, had to use an older version that does not support the feature I have mentioned above.
Any help you can provide would be much appreciated!
Thanks to you all!
Answer by landon912 · Oct 05, 2015 at 07:03 PM
Unfortunately, you can't do this with C# unless the mods are complied into a .dll. You could also look into using an interpreted language, like Lua, that doesn't need to be complied.
Your answer
![](https://koobas.hobune.stream/wayback/20220612040127im_/https://answers.unity.com/themes/thub/images/avi.jpg)