How to execute a string C# code in as unity script?

Hi guys. I am new to Unity.

I want to run/execute the code in another script, let say I want to run it inside of Load.cs

Is it possible to execute a string code like below ?

string script = @"
    using UnityEngine;
    public class GenerateCube : MonoBehaviour
    {
        void Update()
        {
            Debug.Log(""Generate Cube"");
        }
    }
";

You’d need to run a c# compiler from your runtime code. Doing a quick google search (crazy, right?) I found this:
Compile code by using C# compiler - C# | Microsoft Learn
But before ju jump into compiling c# in your app, consider this:

  • Anything you compile will have a form of assembly. Assemblies can only be loaded to the AppDomain, never unloaded. Once it’s loaded, it’s there forever. So if your project ,or whatever your use case for this is, expect to update these regularly, you might have a problem with all the old version remaining present. Unless you want to recreate your own AppDomain every time, in which case you won’t be able to just have a MonoBehaviour class that you can attach to a gameObject and you’d need marshalling.

  • Your code would not be debuggable by default.

  • It would pose a serious security issue. Where is the string coming from? Can you trust it? Can you trust the source not to be compromised, even if it’s coming from your local computer?

Perhaps all you need is some simple expression evaluator. DotNet has a solution for that, and there are some 3rd party solutions too, and they don’t have the issues mentioned above.
Perhaps you would be fine with embeding another scripting language. MoonSharp is a recreation of LUA that runs in managed memory environment and allows for easier binding to c# code. Making a MonoBehaviour wrapper for MoonSharp is quite straightforward, and again, you don’t suffer from the pemanence of loaded assemblies. Otherwise, debugging and security issues would remain similar to compiling c#, though you might have some control over its permissions (as you have when loading assemblies, you just need to be aware of that).

Would you care to share your motivation for doing it?

@Pangamini thank you so much i really appreciate it your help.

I just make a simple experiment with kind of stuffs like embedding and generate dynamic scripts

A i can run the script code from the string by Rosalyn
But in a few cases some of code couldnt found ,because its running on Rosalyn not in Unity,
Let say i have a a script that had public class CustomComponent, and i invoke that in my String code


cube.addComponent<CustomComponent>()



Or even cube.addComponent<Controller>();

Unfortunately it couldnt detect it. I am still looking for a new solution since i am really new in C# ,i ve just touched it in about two weeks

Edited : actually i had solved it already