Search code examples
arrayshaxehaxeflixelhaxelib

Storing objects in array (Haxe)


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

Solution

  • 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