Skip to content

Roslyn C# Integration

scottyboy805 edited this page May 5, 2022 · 4 revisions

Roslyn C# and dotnow setup guide

You can find a useful setup guide Here which covers how to setup Roslyn C# and dotnow so that they can work together on IL2CPP platforms like WebGL or Android.


dotnow includes a number of scripts to integrate seamlessly with the Roslyn C# runtime compiler, available on the Unity asset store. Integration with this asset will allow you to compile and execute code at runtime on Il2CPP platforms.

There are a few steps to enable the integration:

Import Roslyn C#

Use the Unity package manager to download and import the latest version of Roslyn C# into your project, if it has not already been added.

Enable Integration Scripts

Integration scripts are disabled by default because not all users will have the compiler installed. The scripts can be enabled simply be adding a compiler define symbol to the player settings.

  1. Open the Unity project settings window (Edit -> Project Settings).
  2. Select the 'Player' tab in the left side panel.
  3. Scroll down until you find the field labeled 'Scripting Define Symbols'.
  4. Add 'ROSLYNCSHARP' to that field and hit enter to recompile scripts.

Usage

A number of extension methods will now be available for the ScriptDomain type. These extra methods will always include the term 'Interpreted' for clarity, and you can swap out existing code with the interpreted replacement to cause C# scripts to run using the interpreter rather than being JIT executed.

The following code:

// Create a script domain
ScriptDomain domain = ScriptDomain.CreateDomain("JIT Domain");

// Compile and load as JIT code
domain.CompileAndLoadMainSource(...);

would become:

// Create a script domain
ScriptDomain domain = ScriptDomain.CreateDomain("Interpreted Domain");

// Compile and load as interpreted code
domain.CompileAndLoadMainSourceInterpreted(...);

You will find that all normal Roslyn C# compile methods will also now have an interpreted counterpart. You are not just limited to compiling from source.

That is all you need to do. You will then be able to find types and members as you would normally using the Roslyn C# scripting API, and any invocations will be executed by the interpreter. No need to work at a low level unless you really want to, as all the details are abstracted away.> *

Clone this wiki locally