Hello.
From my own experience Array<Dynamic>
works fine on flash, but on android it’s kind of sketchy.
var array:Array<Dynamic> = [];
var box:Sprite = new Sprite();
box.graphics.beginFill(0xFF0000);
box.graphics.drawRect(0, 0, 32, 32);
box.x = 100;
box.y = 100;
stage.addChild(box);
array.push(box);
trace(array[0]); // flash return: [object Sprite], android return: [object Sprite]
trace(array[0].x); // flash return: 100, android return: null
When I push a sprite in Array<Dynamic>
and I want to access it’s x, y, width or height it just returns null on android. In flash it all works fine.
If I change Array<Dynamic>
to Array<Sprite>
it will work great on both platforms but I really need it to be dynamic.
//Works on Android but not Flash:
trace(array[0].get_x());
//Works on both:
trace(Reflect.getProperty(array[0], "x"));
//Works on both:
trace(cast(array[0], Sprite).x);
OpenFL has a getter and setter for the Sprite.x
field. That means that there’s a get_x()
and set_x()
function, and you’re supposed to use those instead of accessing x
directly.
So why can you use x
normally? Shouldn’t it always fail?
Well, the Haxe compiler makes that replacement for you. When you type sprite.x
, the compiler replaces it with sprite.get_x()
. Since the get_x()
function exists, everything works as expected.
The problem is, the compiler can’t tell if a Dynamic
object is supposed to use a getter, so it assumes not. It won’t replace dynamic.x
with dynamic.get_x()
, and then at compile time, it tries to access x
on an object that doesn’t have an x
field. That’s why it returns null
.
Here’s how the three solutions work:
- If you explicitly type out
get_x()
, then of course it will use that function. Problem is, that function doesn’t exist in Flash, so it won’t work in Flash.
-
Reflect.getProperty()
checks for a getter function. On Android, it’ll find a getter, and use that. On Flash, it won’t find a getter, so it’ll just use the x
field. This is a bit slower, but it covers everything.
- If you tell the compiler that this will be a
Sprite
, then it will know about the getter, and it’ll replace x
with get_x()
on non-Flash targets. But the object has to be an actual Sprite
, which kind of defeats the point.
Thank you @player_03, you were more than insightful with your reply.