Execute String as Code Line?

I’ve got a script, which will be reused in many different situations (A Dialogue Script). The most important thing is - at the end of the dialogue, there will be different events planned to occur (LoadLevel, Destroy GameObject, Instantiate etc).

Logically, the basic way to do it is to create a new script for each dialogue - with 90% of the same code as others, but with different “ending function” code lines. But then I thought if there’s a way to implement a String to be executed as a line of code, so it can be changed in the Inspector - on the same token, creating one, universal and Insector-editable script for all dialogue objects.

Visualisation:

var EndingLine1 : String = "Destroy(GameObject.Find("ThePlayer"));";

function EndingFunction()
{
EndingLine1;
}

Lazyness, the mother of invention. :stuck_out_tongue:
The problem is - the normal String is, of course, just a variable. So a standard “Expressions in statements must only be executed for their side-effects” Error.

Ideas?

1 Answer

1

Fortunately as you appear to be using javascript you can use the eval command which is built in to do this. If you go the c# route it is a bit more complicated :frowning:

var command : String = "UnityEngine.Object.Destroy(gameObject)";

function Start(){
	eval(command);
}

Aaah, splendid! Exactly the command I was looking for. Thanks a ton! :D

–