//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 thexfield. 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 replacexwithget_x()on non-Flash targets. But the object has to be an actualSprite, which kind of defeats the point.
