Can I use a variable in another variable name?

I have a quick javascript question.

I’d like to use a variable as part of another variable name. I have 4 players. And a variable, playerSelected = 1 (2, 3 or 4).

I also have variables such as:

player1Sword = 1;
player2Sword = 0;
player3Sword = 0;
player4Sword = 0;

Rather than doing…
if (playerSelected == 1) etc for each player, I’d like to do something like:

player[playerSelected]Sword = whatever

Is that possible?

Sort of. You should probably use Arrays or Lists to accomplish your goals here.

Haven’t tested this exactly (I’m not sure how Unity checks this and what’s the scope it’s attributed to, but try:

this["player" + playerSelected + "Sword];

Because, in JavaScript,


Is the same as:


Which is the same as:

var c = "b";
If all fails, you can try using [eval][1] for that. This would be a last resort (using `eval` is, overall, a bad idea). And again, I'm not sure if Unity supports it.

The real answer, though? You shouldn't do any of that. Trying to store properties like that is a terrible convention. You should have everything in arrays, objects, hashmaps, or what have you, and then reuse it from that. Something like:

    players = [];
    players[0] = {sword:0};
    players[1] = {sword:1};
    players[2] = {sword:0};
    players[3] = {sword:0};

Then you'd access that with:


You could even initialize that in one go, with

    players = [

Or what have you for your data (of course using custom classes would probably be better, depending on how complex your data model is).