Use of runtime compiled code.

Hello,
I want to fiddle around with runtime generated and compiled code, preferably directly inside application. After looking around I found out that my best bet is to use Roslyn but I just can’t get it to work nicely with Unity.

So what’s would be a proper way to do it in Unity?

If that matters, I wish to play around with designing GUI based overlay/ graphical programming language that would generate c# code. But for that I have to do runtime code compiling and assembly reloading first.

So, any ideas?

Cheers

What’s your goal here? If this is intended for you or other developers to create and run C# code, why do you want it to run in a runtime app? Why not make, for example, an editor window that can drop the generated code into the project folder and let Unity compile it?

I say this because “compiling C# in runtime” is a really difficult problem - it’ll be hard to incorporate in the first place, even harder to make it work on multiple platforms, impossible to distribute on some platforms (iOS and Android are right out, probably most other storefronts too), and if you want to support new versions of C# you’ll have to go through all of that repeatedly every time you update. And you’ll save yourself a world of hurt by just skipping the compiler entirely. And it sounds very skippable.

If you’re not absolutely committed to this being a C# tool, there are runtime scripting languages with easy support in Unity that avoid every single one of these problems. If it must be a C# tool, surely an editor window is more useful.

So, it seems using C# in this case is more pain than gain.

Could you point me to “runtime scripting languages” that can be used with Unity? I would like to cheek if they offer what I’m looking for. Or, if I would need to go “csc.exe” rabbit hole.

Compiling at runtime is pretty easy, and can be done with the CompileAssemblyFromSource method from the CSharpCodeProvider type. Its something that has been possible for a while now, the only issue is you cant unload the code once its on the appdomain

Hands down the least painful integration wise will be something like MoonSharp LUA. There’s even an asset store package, or you can integrate it yourself however you like.

Be sure you answer starmanta’s question here:

Before you launch down a massive rabbit hole of language and compiler integration (and it is a never-ending rabbit hole, constantly collapsing into itself every time someone updates the language or the runtimes!), ask yourself what value your app would provide above just downloading Unity and following basic C# tutorials.

2 Likes

Considering how problematic compiling seems to be. I will focus for now on code generation part of the project, and see what I can achieve there.