简体   繁体   English

将对象存储在数组中 (Haxe)

[英]Storing objects in array (Haxe)

How would I go about sorting an new instance of an object into an array in Haxe?我将如何将对象的新实例排序到 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

I think you are looking for this:我想你正在寻找这个:

private var inventory:Array<Weapon>;

This is an array of type Weapon .这是一个Weapon类型的数组。 To add stuff to it use push() , as seen in this example:要向其中添加内容,请使用push() ,如下例所示:

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演示: http : //try.haxe.org/#815bD

Found the answer must be writen like this发现答案一定是这样写的

private var inventory:Array;私有变量库存:数组;

With Weapon being the class name.武器是类名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM