1

How would I go about sorting an new instance of an object into an array in Haxe?

For example I have a class called weapon and in the player class I gave an array inventory. So how would I store this?

private void gun:Weapon

gun = new Weapon; //into the array
Kev
  • 15,899
  • 15
  • 79
  • 112
  • Please edit your question so as to include the code you have already tried, and an explanation of how it is not working. Also, you may find this helpful: [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask). – MJH Oct 14 '16 at 04:01

2 Answers2

3

I think you are looking for this:

private var inventory:Array<Weapon>;

This is an array of type Weapon. To add stuff to it use push(), as seen in this example:

class Test {
    static function main() new Test();

    // create new array
    private var inventory:Array<Weapon> = [];

    public function new() {
        var weapon1 = new Weapon("minigun");
        inventory.push(weapon1);

        var weapon2 = new Weapon("rocket");
        inventory.push(weapon2);

        trace('inventory has ${inventory.length} weapons!');
        trace('inventory:', inventory);
    }
}

class Weapon {
    public var name:String;
    public function new(name:String) {
        this.name = name;
    }
}

Demo: http://try.haxe.org/#815bD

Kev
  • 15,899
  • 15
  • 79
  • 112
Mark Knol
  • 9,663
  • 3
  • 29
  • 44
1

Found the answer must be writen like this

private var inventory:Array;

With Weapon being the class name.