Giving each object that share the same class, their own individual variables that won't affect the other variables

StackOverflow https://stackoverflow.com/questions/22976628

Frage

Good Evening/ Morning.

This is a games related question.

I am facing an issue where I have three objects, (three goblins) data typed to the same class.

These three objects are in an array and data typed to that class, and initialized as the array.

    private var goblin1:Goblin = new Goblin();
    private var goblin2:Goblin = new Goblin();
    private var goblin3:Goblin = new Goblin();

So the variables above have been then placed into an array.

    private var aGoblinArray = new Array(container.goblin1, container.goblin2, container.goblin3);

After placing the objects into an array I have looped through all of my goblins.

    for (var i:int = 0; i < aGoblinArray.length; i++)
    {
        var goblin:Goblin = aGoblinArray[i];
    }

now I have a hitTest in the for loop and the hitTest is:

                if (goblin.hitTestPoint(_character.x + 100, _character.y - 45, true))
                {
                    goblinCanMove = false; 
                    trace("lance hits");
                    //hitOnce
                    if (!hitOnce)
                    {
                        hitOnce = true;
                        trace("take on damage");
                    }
                    goblin.moveBack();
                    goblin.minusHealth();
                }

This means if this player hits any of the goblins, they will do this function.

How ever in the goblin class.

    public static var goblinLife; int;

    goblinLife = 2;//put in main constructor 

    public function minusHealth():void 
    {
        goblinLife --;
        checkDeath();
    }

    private function checkDeath():void 
    {
        if (goblinLife == 0)
        {
            parent.removeChild(this);
        }
    }

the problem is, if I hit goblin1, then goblinLife would = 1. This means all othet goblins(goblin2 and 3) will have 1 life. Since they share the same class.

if goblin1 dies, he is removed and the var goblinLife would = 0; Now I can reset it back to 2, but this will fix half of the problem.

My question is, is there a way on how I can make sure each goblin has it's own individual life system. Thank you in advance.

War es hilfreich?

Lösung

Thank you very much Pan and Marty!

Static meant that it could be changed from any class and any function.

Private means that it will be protected to each individual goblin.

From changing

    public static var goblinLife; int;

to

    private var goblinLife; int;

it means that each individual goblin will have their own variable, that no other class or object of the same class can change.

Thank you Pan and Martyn. I guess I need to read AS3 101: Quick Tip – When to Use Static Properties and Methods and other coding books!

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top