- Home /
Text being part of a function?
I hope this makes sense. Is there a way to have a variable, which corresponds to a string of text, and the string of text is a piece of code? Something like this(its for a turn based RPG)
var A = 0; var B = String;
function Start (){
Invoke"ATTACKPHASE1",3);;Invoke"ATTACKPHASE2",3);
}
function Update (){
if(A==1){B=HP-=10;MP+=5;}
if(A==2){B=DEF-=2;MP-=3;}
if(A==3){B=HP+=20;DEF+=5;}
}
function ATTACKPHASE1(){ //this is where the player chooses what attack they want to do by picking a value for A, this would be done through the GUI, lets say for this example, they set A equal to 3 }
function ATTACKPHASE2(){
//Enemy is the name of a script with public HP/MP/DEF variables in it
Enemy.A
//so that would be like Enemy. HP+=20;DEF+=5;
}
if the variable=string=function isnt possible, how would I make a string of text represent something in a function, so I could do Enemy."B"
Thanks
Answer by CHPedersen · Apr 12, 2011 at 10:57 AM
That's not possible, no. :)
If you want to execute a different piece of code depending on the value of B, you need to either set up a series of if-statements or construct a switch over B. Remember that because code is compiled, you cannot inject source code in particular places at runtime; that's the wrong way to think about programming. :P
It seems to me that A corresponds to different scenarios that can happen in your game. Consider declaring an enum to represent these scenarios, and then switch over them, executing the appropriate action you're trying to store in B under each switch case.
This is semantically equivalent to a series of if-else if statements. If you decide to go for if-statements instead, notice that, for example,
if(A==1){B=HP-=10;MP+=5;}
if(A==2){B=DEF-=2;MP-=3;}
if(A==3){B=HP+=20;DEF+=5;}
Should be
if(A==1){B=HP-=10;MP+=5;}
else if(A==2){B=DEF-=2;MP-=3;}
else if(A==3){B=HP+=20;DEF+=5;}
Since there is no need to ask if A is 2, if you've previously ascertained that it is 1, and so on.
Your answer
Follow this Question
Related Questions
Reference other scrips in prefab 1 Answer
Sort a list by apparition 0 Answers
Ammo Script 1 Answer
Text to Variables 2 Answers