- Home /
Accessing Dynamically Named Variables (javascript)
So need to read some variables that are in a static class. The variables are just strings named Lock1 through Lock4. Their values are either locked or unlocked. I've been trying to do this without a bunch of if else statements in case more locks need to be added to the game. So what I want to do is to ask the global script for a variable with something like:
function GetLock(lockNum : int) : String
{
//return value of "Lock" + lockNum
}
I've tried a few keyworks like pathTo and nothing has worked so far.
Answer by Waz · Jul 24, 2011 at 11:00 PM
You can't. Either change the variables to an array:
var Lock = [0,0,0,0];
(and note that arrays start at 0 not 1).
or use a switch to read them:
function GetLock(lockNum : int) : String
{
switch (lockNum) {
case 1: return Lock1;
case 2: return Lock2;
case 3: return Lock3;
case 4: return Lock4;
}
}
I would recommend using the array.
Answer by aldonaletto · Jul 24, 2011 at 11:04 PM
You can't do these typical javascript tricks in Unityscript - variable names cannot be dynamically created or modified. You must use an array if you want to access the variables by index.
Your answer
Follow this Question
Related Questions
Dynamically call variables 2 Answers
Create variables dynamically 1 Answer
Card Game Unique abilities run dynamically 2 Answers