Accessing instances store in swf file by name

In actioscript 3, I can access an object instance by using a string with the instance name. For example if I have a sprite called background and it contains an object named myObj I can access it with

obj = background["myObj’];

This is very useful if there are multiple objects of the same type with names myObj1, myObj2, myObj3, etc. I can access any one of them by number with:

obj = background["myObj’ _ String(number)];

What’s the equivalent of this in OpenFl/Haxe?

Are your assets coming from a SWF file?

Are you using the generate="true" option to generate classes for your exported symbols?

If you did generate and do use the class types, you can reference it directly:

obj = background.myObj;

However, if you are not (or need to dynamically come up with the name), but are using SWF-based assets, the fields are dynamically assigned if you compile using -Dopenfl-dynamic:

obj = Reflect.field (background, "myObj" + number);

For any other type of object, you should always be able to use getChildByName, like this:

obj = background.getChildByName ("myObj" + number);

Thanks, that worked. Using obj = getChildByName forced me to coerce the correct type which is a pain compared to using “as” in actionscript. With Reflect I didn’t have to coerce but the documentation for Reflect said “Use with caution.” What should I be concerned about?

It could crash if you reference a field that doesn’t exist, if you aren’t use, use something like Reflect.hasField before using Reflect.field.

Reflection also varies a bit per platform, but its generally safe (we use it in Actuate, for example)