Is there a way to edit the code in a script during runtime?

I want to have an AI in my game that can edit it’s own code as it acts during runtime. Is this even possible or am I just crazy? I’m thinking that I could use System.IO or something similar.

Yes you are being a bit crazy. The code would have to be compiled before it can be used. Your script files aren’t the actual final code before it has been compiled down into IL mush into a .dll file for runtime use. I don’t believe there’s a mechanism to do this in a build.

There is no doubtably better ways to do what you probably want to do.

Dynamically generating code can be done by using the classes at System.Reflection.Emit namespace. This is being used for example in Entity Framework Core to generate proxy classes for lazy loading and it is possible for JIT compilation.

Methods can be generated either by using the DynamicMethod class or for more complicated tasks like creating whole types the Typebuilder class.

This is extremely difficult programming as you have to know IL assembly. Instead of idiomatic or even lower-level C#, you code in IL assembly by manually emitting opcodes and pushing and popping values from the stack. This means that handling your variables is hard at best and there are no branching options like while, for and so on, instead everything is done with GOTO’s.

Besides the above, you need to have a perfect knowledge of the whole pipeline of compilation from how to create and handle the internals of assemblies, to defining types, to creating constructors in IL etc.

Look at decompiled code with a tool like ildasm or the IL generated code at sharplab, if you can understand what it does by reading it without reading the C# code, then maybe you have a chance of creating code dynamically.

So the answer to both your questions is yes, it can be done and also it is extremely crazy, but for a complicated task like AI that changes its own code, even if you can not only read, but also write correct IL code, is like fixing the engine of a moving car, while racing, with your hands behind your back, using you mouth to handle the necessary tools and controlling the wheel with your foot, …blindfolded.

1 Like

alternatives:
Use other languages, like LUA, Miniscript, some python interpreters have been available too…

also theres been few of these,