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,

a.b

Is the same as:

a["b"]

Which is the same as:

var c = "b";
a
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:

    players[0].sword

You could even initialize that in one go, with

    players = [
        {sword:0},
        {sword:1},
        {sword:0},
        {sword:0}
    ];

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


  [1]: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval