I have no idea why haxe is working this way. I have sprite and it’s childs. and when I get child I can’t use it’s methods becouse it’s displayContainer not my class:
this.Player.Board.getChildAt(i).lightsDown();
return error:
openfl.display.DisplayObject has no field lightsDown
when you do this.Player.Board.getChildAt(i).lightsDown(); it can be any i
and there’s no way for the compiler to get more informations, who knows what kind of class will be pushed as child.
And when you do Type.getClass( this.Player.Board.getChildAt(i) ) then you are asking the runtime the type of this specific i.
but both are in the same loop. it’s the same i so I don’t really get the difference ;/
is my aproach with cast a good way to do it? or should I do it in some other way?
now I do it like this:
for (i in 0...this.Player.Board.numChildren) {
if(Type.getClass(this.Player.Board.getChildAt(i)) == Hex)
cast(this.Player.Board.getChildAt(i),Hex).lightsDown();
}
var hex:Hex;
for (i in 0...Player.Board.numChildren) {
hex = cast Player.Board.getChildAt (i);
hex.lightsDown ();
}
If you don’t know the type:
var hex:Hex;
var object;
for (i in 0...Player.Board.numChildren) {
object = Player.Board.getChildAt (i);
if (Std.is (object, Hex)) {
hex = cast object;
hex.lightsDown ();
}
}
You could also use your own array to keep track of your objects. This is common. Instead of only calling addChild, use tiles.push as well:
public var tiles = new Array<Hex> ();
...
var hex = new Hex ();
Player.Board.addChild (hex);
tiles.push (hex);
...
for (tile in tiles) {
tile.lightsDown ();
}
By keeping your own list, you keep the objects strongly typed, making it simpler to iterate through, without needing to cast
Sorry, I forgot to delete a cast when I copied and modified the original sample.
I meant:
var hex:Hex;
var object;
for (i in 0...Player.Board.numChildren) {
object = Player.Board.getChildAt (i);
if (Std.is (object, Hex)) {
hex = cast object;
hex.lightsDown ();
}
}
…and technically you can do the vars inside the for loops, it’s a bit shorter to read that way, but using one variable can perform better, and prevent a stack overflow in C++ for very large loops