-
hi,
i'm currently doing some stuff for a flash game and have come across an odd problem...
heres the relevent lines of code...
var statsAry = new Array();
statsAry[1] = {utype: "tank", movespeed: 2, ap: 100, hp: 250, mcost: 50, fcost: 50, damage: 75};
_root["unit"+numunits].stats = _root.statsAry[1];
there can be multiple units with the same stats, so i thought the above would be a nice clean way of generating their details
thing is though, when you get into the game and start changing the values e.g.
_root.unit5.stats.ap = 50;
it not only changes that unit, but all other units of the same type *and* the initial root array?? why?? :/
-
array variables are "pointers" to the array in memory. If you have:
arrayOne = [1,2,3,4,5];
then the variable arrayOne is pointing to a block of 5 variable values (numbers) somewhere out in your computers memory. When you try to assign another variable name to be that array ie.
arrayTwo = arrayOne;
Then that new variable will get the pointer aspect of the old one, where it would then point back to that same block in memory and each arrayOne and arrayTwo would be accessing and changing the same values.
To prevent this, you need to make a copy of the array. In flash you can do this using the Array objects slice method which extracts a portion (or all) of the given array and returns it as a new array.
arrayOne = [1,2,3,4,5];
arrayTwo = arrayOne.slice();
arrayOne[0] = "a";
trace(arrayOne); // a,2,3,4,5
trace(arrayTwo); // 1,2,3,4,5
-