Dynamically generated/edited scripts?

I am making a simple multi variable function grapher, and I can’t figure out a good way to let the user enter a function. The best that I can come up with would be to just let them enter the equation into a text box in plain text, and then run a separate script to parse the input, re-write it in the equivalent C# syntax, generate a new script with that code put in, and then run that script to generate the graph. Are there any better ways to do this? This is a very messy system, and I’m not even totally sure how to have one script generate another.

On a related note, is there any where in a shader that you can place code to run once at initialization and never again? Because otherwise I’ll have to have a script auto-write shaders.

You want a script interpreter to run user created scripts at runtime.

Moonsharp is a pretty cool LUA interpreter that can execute lua scripts at runtime. It interfaces with Unity rather well. I’ve only played with it a bit, but it works well.

There are a few C# interpreters out there. I haven’t used any, myself. A quick google search turned up GitHub - keyworq/CSharp-Interpreter-for-Unity-3D: C# Interpreter Console for Unity 3D which seems promising.

I bet there are interpreters for python and other scripting languages that can work with unity’s version of mono.

A typical way to implement mod support is to introduce an intermediate language like LUA or MiniScript. There are bindings for Unity around. Otherwise it is just straight up parsing the language that the user types in.

You can use reflection to create IL at runtime on some platforms, but I would strongly suggest not doing this. You don’t want to give the user full access to C# classes in your game.

Which leaves you back at parsing through some intermediate language.

When you’re saying a function, do you mean something like this:

f(x) = (x ^ 3) - 3x + sin(x)

Or something like:

float Foo(int bar) { ...

Since you’re talking about function graphers, I assume it’s the first one, but it’s better to be sure.

I mean the first one. It’s super easy to let users pass variables to the script, and by extension it’s super easy to just let them type out “f(x) = sqrt(x)”. I can fairly easily (if messily) automatically convert that to read “double y = Math.Sqrt(x);”. But I’m not sure how (if it’s even possible) to then run that code

You can run that code (through runtime compilation), but it’s kind of messy. It’s also not allowed on any of the mobile platforms.

A much better (probably) approach is to parse the function text into some structure, and then evaluate that structure. You’re essentially defining a maths-based dsl.

Of course, the very easiest thing would just be to let someone else do it for you. NCalc looks easy to use. This library explains what’s going on, which is probably usefull if you want to roll your own.

1 Like