Parsing string as code (C#)

So I want to build this little code sandbox in Unity, which would allow me to teach students the basics of algorithmics and coding.

The idea would be for them to enter (very basic) code in a text box or something of the kind, and to observe the effects of their code onto objects present in a Unity scene. I’m pretty sure this has been done a million times, but I’d love to try my hand at this. The rub is, I have no idea where to start…

I guess the idea is that the string would be compiled into code & executed at runtime, at the press of a button.

I’ve read about numerous other questions on SO, and have come up with very diverse solutions such as using a C# parser, reflection, expression trees, CodeDom, etc.

From what I understood of all these (i.e., not much), CodeDom seemed more appropriate, but then I read that it only ran inside of Visual Studio and generated errors in public builds. So does that mean that this is going to be a problem within Unity3D (as it is based on Mono?)

Thank you for your help,

I researched this theme some time ago and found several solutions. I am still not sure which solution is better. But they are works.

The answer can be found in the Asset Store by simply searching for “C#”

The first solution is: Unity Asset Store - The Best Assets for Game Making

I tested it and it works very well, but with one important flaw. It works in Unity editor but can’t be build due some error about lack of some Mono library.

Also, you may notice that author of this asset said in the description that he is recommend to use alternative solution, which is located here: GitHub - JakubNei/mcs-ICodeCompiler: Fully C# mannaged ICodeCompiler implementation that uses modified MCS (Mono C# compiler) usable in Unity.

This link on GitHub contains Unity project with working solution which works well both in Unity editor and build. Also it contains detailed explanation about why it have some complications during build and how author solved this problem.

The problem is, that second solution (in my opinion) is much harder to understand and work with. Besides that, I can’t figure out how to compile several scripts at once (not only one) and author of this solution is not very active on the forum.

Anyway, I recommend you to check both links and see how it made, also check various links provided by authors of this tools.

In addition, in Asset Store you may find even more tools.
For example this: Unity Asset Store - The Best Assets for Game Making

But I discovered it only now and haven’t used it yet. Also it is not free.

But besides that, also you may found plenty of similar tools, not for C# but another languages.

For example:

Java:

Lua:

Python:

I tested only Java, it works very well. But of course, C# will be better for education.