How can I import C# scripts during runtime?

In my game I want to introduce modding in the form of putting C# scripts in a folder in the game files, but I’m not all too sure how to grab C# files from a file location and load them into the game.
I want to be able to do this in the actual built version of the game rather than the editor, so that’s why I wasn’t able to find out how from a simple google search (for some reason, everything I found was on loading the scripts in from a file location for the game in the editor).
After about a month of trying a ton of different things, I’ve decided that I should go to the more experienced people in unity and C# and get your help.

Do any of you know how I can pull this off?

You would need to have a full C# compiler and SDK shipped and installed with your game.

You’re welcome to try your hand at that gargantuan task but it will NOT be easy, and it will not work on iOS or Android simply because code cannot run on those targets unless it is digitally signed.

You could do a lot of modding with something like LUA however. This is a package I have used in Unity:

https://www.moonsharp.org

4 Likes

Unity builds don’t include a C# compiler or any C# code. Your C# scripts in your build are already compiled when the build was created.

As Kurt was saying with LUA, consider using a runtime scripting package if your modders need to be able to write code.

Often mods for games just consist of swapping out assets and changing existing values for things. That can be accomplished by storing the values for everything modable in a text format (JSON, XML, custom format, etc), and either runtime loading of obj models and textures, or letting modders create their own Asset Bundles which you import.

1 Like

Alright. I only assumed that it was possible because the unity game People Playground handles modding in the form of C# scripts, but now I know that it isn’t built in functionality with unity and is probably hard to develop.

I was also thinking of as an alternative letting the modders instead do a text file with the code in it as text, and then I would grab that as a string and build it as C# code using a method similar to what was done early on in this video:

. The only reason why I haven’t done this already was because I thought it would be a bit weird of a way for the modders to have to script.

I’ll also try and look into the moonsharp thing, that should be useful.

1 Like

Just let a search machine look for “C# eval”.
reflection - How can I evaluate C# code dynamically? - Stack Overflow the first comment with 2 links
C# Eval Function - CodeProject
C# Eval() support - Stack Overflow
"eval" in C#, yes it's possible - Ckode.dk
But as already mentioned this is a non-trivial undertaking.

There are at least 2 Assets for modding at the AssetStore. But I don’t know if and how they allow code modding. But you could have a look.