c# Eval()?

Is there anyway of taking a string and parsing it as code?

like

public string str = " if (1 == 1) { a = b; } ";

ive had a look on google apparently there are ways of doing it but its confusing! so i wondered if anyone could explain it better or give me an example?

Thanks


EDIT:

in a Custom Editor Textarea(string) the user could write

varX = 5;

or

if (1 == 1) { //do this }

if that is written in the textarea, it will be saved as a string

what im trying to do is take that string, and run whats inside it (in laments terms from “varX = 5;” to just varX = 5; so that it will actually parse the code as code not a string

I found it may need other Class like Jscript.NET,
but I don’t know it is suitable for U3D or not?

You can’t do this in C#, the closest you can come is to use reflection to get a property, and then envoke it. but that’s not going to help you evaluate straight up code.

What are you trying to do, anyway? There may be a better way of doing it that you might not have thought about.

If you absolutely need to do something like your example, and you have a predictable set of information, you could just parse the string and evaluate it manually.

edit: here’s a guy on codeproject who has done just that (written a manual parser/evaluator), could help you get started:

Why don’t you say that you write an editor script? At runtime the compiler isn’t available because it isn’t part of the engine, but in the editor you can just save your code in a .cs file and let it compile by Unity like any other script.

The question is why do want to do this yourself? In a proper editor like VisualStudio you can write you scripts much faster and have intelliSense. You can of course create some kind of template script and insert the code into a special method and save the script as seperate file.

Take a look at the MonoScript class. It represents the text part of a script asset. It also has a function (MonoScript.GetClass) that returns the Type-Object for the containing class which can be used with AddComponent.

The compiling takes some time so you have to find a way to do all that smoothly. EditorApplication.isCompiling might be helpful.