- Home /
String as Variable name
The OpenClose script will be on every door and there will be more than 3 doors/keys so I'm trying to use a string as a variable name from the CharInventory script.
The doors are not in order(the keys are named as example).
//Script: CharInventory
var key1 : int = 1;
var key2 : int = 0;
var key3 : int = 0;
//Script: OpenClose
var keyNeeded : String; //This will be different for each door( key1/key2/key3 )
var charInventory : CharInventory;
//Everything between is fine
function OnGUI(){
if(GUI.Button(Rect(Screen.width / 2 - 25, Screen.height / 2, 50, 25), "Use Key")){
if(charInventory.keyNeeded >= 1){ // <<<<<< How do I use the string to check CharInventory?
//Unlocks the door
}
if(charInventory.keyNeeded <= 0){ // <<<<<< How do I use the string to check CharInventory?
print("Need a key");
}
}
}
this may need something related to Reflections if you need to check variable name, but i will suggest you to do it by using array
for 1, create an array in inventory script to hold the three variable, say:
public int[] keyArray = new int[3];
then in your openclose script set int for key needed:
int keyNeeded= 0; //this means need key1, key2 is 1 and key3 is 2
and check by:
if(inventory.keyArray[keyNeeded]>=1){...}
something like that.
So how would you add a key to the inventory keyArray from another script?
say, add key to key1:
inventory.keyArray[0] += 1;
that's it~
You can also set a function in the inventory script:
public void get$$anonymous$$ey(int keyIndex){ keyArray[keyIndex] += 1; }
and an enum
public enum $$anonymous$$EYINDEX{ $$anonymous$$EY1, $$anonymous$$EY2, $$anonymous$$EY3, $$anonymous$$EYBOSS, $$anonymous$$EYTREASURE }
something like that, to help you on the arrayIndex and $$anonymous$$ey matching, so you don't need to remember what key is keyArray[0] anymore.
Now you can Call:
inventory.get$$anonymous$$ey((int)inventory.$$anonymous$$EYINDEX.$$anonymous$$EY1);
to get a key1