Static constant variables are changing


(Zouhair Elamrani Abou Elassad) #1

I have a Gameconstants class where i keep my constants :

public static const LIFE_POINTS_X:Array = [880, 1080];		
public static const LIFE_POINTS_Y:Array = [200, 200];

And i have a Globals class where i keep my variables, some of theme get their initial values from my Gameconstants class :

        public static var lifePointsX:Array = Gameconstants.LIFE_POINTS_X;	
        public static var lifePointsY:Array = Gameconstants.LIFE_POINTS_Y;

The idea is that i want to place on my stage some life points for my player who to takes, the player has 3 lifes maximum and if he touches an object he loses one, and once he takes a life point i add it to his life points and i remove it from stage, but if he loses all his life points he’s dead i restart the game and i place all the life points back to stage.

I keep to coordinates of the life points in a static array (i don’t know if it’s the best idea), if the player takes a life points i remove it from the Global array using splice, and if the player loses i place them all using the coordinates from the Gameconstants.

The problem is at game restart i find that the Gameconstants variables are modified as well and not all the life points are places in the stage, this is my code:

                       _LifesBonus = new Vector.<LifeBonus>;
			getType("lifeBonus", _LifesBonus);

			var lifes:Vector.<LifeBonus> = _LifesBonus.reverse();

			for (var i:uint = 0; i < lifes.length; i++) {
				
			      var life = _LifesBonus[i];
			
			      if (life.collideWith(_player, life.x, life.y)) {
						
					Globals.playerHealth++;							
					Globals.lifePointsX.splice(i, 1);
					Globals.lifePointsY.splice(i, 1);

					recycle(life);
				}
			}

When i restart my game i reload my world :

FP.world = new MyWorld();

and i call this function :

public function initLifePoints():void {
					
		var X:Array = Gameconstants.lifePointsX;	
		var Y:Array = Gameconstants.lifePointsY;

		for (var i:uint = 0; i < X.length; i++ ) {
			add(new LifeBonus(X[i], Y[i]));
		}
	}

(Jacob Albano) #2

In as3, const just means a property can’t be assigned to. Making an array constant is kind of pointless since you can perform all the operations on it to modify its contents anyway.


(Zouhair Elamrani Abou Elassad) #3

I see, but the issue is that when i delete from the array, i do that to the Global array not the one in Gameconstants, then why in the world that Gameconstants is changing?


(Jacob Albano) #4

Your global array is a reference to the one in Gameconstants. Deleting from one will delte from the other, since they both refer to the same object.


(Zouhair Elamrani Abou Elassad) #5

I see now, thank you so much :smile: