Hi Everyone!
I hope someone can help with a tricky problem I’m facing. I’ve done a lot of research but haven’t found a solution yet. Here’s a very basic version of what I’ve been trying solve.
I’ve got 2 MovieClip objects manually added to stage by dragging instances from the Library with these names:
objectOne
objectTwo
Both of these objects are bound to classes called ObjectOne and ObjectTwo. What I want to do is give objectOne a reference to objectTwo.
Here’s what the ObjectOne class looks like:
package
{
import flash.display.MovieClip;
public class ObjectOne extends MovieClip
{
private var _objectTwo:MovieClip;
public function ObjectOne()
{
_objectTwo = parent.getChildByName("objectTwo") as MovieClip;
trace(_objectTwo);
}
}
}
The trace reports “null”
I think I know why this is happening. objectOne is added to the display list before objectTwo. That means when the reference to objectTwo is made, it’s obviously null because it doesn’t yet exist.
The only solution I’ve found to his I’m not happy with. It involves adding an ENTER_FRAME listener and assigning the reference to objectTwo on the very first frame. This guarantees that all the objects have been added to the display list. Here’s what it looks like:
package
{
import flash.display.MovieClip;
import flash.events.Event;
public class ObjectOne extends MovieClip
{
private var _objectTwo:MovieClip;
private var _findStageInstances:Boolean;
public function ObjectOne()
{
_findStageInstances = true;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(event:Event):void
{
if (_findStageInstances)
{
_objectTwo = parent.getChildByName("objectTwo") as MovieClip;
_ trace(_objectTwo);
}
}
}
}
This trace succeeds.
I’ve used the ADDED_TO_STAGE event, but it won’t help in this case because it only fires when this object is added to the stage, not the object it’s trying to reference.
If anyone knows of any better ways to make sure all objects are on the stage before a reference is made to them, I’d love to hear about it!!
Thanks!
- Dandylion13