【问题标题】:Storing objects in array (Haxe)将对象存储在数组中(Haxe)
【发布时间】:2017-02-23 08:58:27
【问题描述】:
如何在 Haxe 中将对象的新实例排序到数组中?
例如,我有一个名为武器的类,在玩家类中我提供了一个数组库存。
那么我将如何存储这个呢?
private void gun:Weapon
gun = new Weapon; //into the array
【问题讨论】:
标签:
arrays
haxe
haxeflixel
haxelib
【解决方案1】:
我想你正在寻找这个:
private var inventory:Array<Weapon>;
这是一个Weapon 类型的数组。
要向其中添加内容,请使用 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;
}
}
演示:http://try.haxe.org/#815bD
【解决方案2】:
发现答案一定要这样写
私有变量库存:数组;
Weapon 是类名。