- Home /
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. :P 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?
Answer by Scribe · Sep 30, 2014 at 05:06 PM
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 :(
var command : String = "UnityEngine.Object.Destroy(gameObject)";
function Start(){
eval(command);
}
Aaah, splendid! Exactly the command I was looking for. Thanks a ton! :D