I am having an issue passing the value of a variable in a parent AS3 script to a child swf called by the parent.
The child also has an AS3 script associated with it.
It is a simple example. Here is the parent script.
package scripts {
import flash.display.MovieClip;
import flash.display.*;
import flash.net.URLRequest;
import flash.events.MouseEvent;
import flash.events.Event;
public class passone extends MovieClip {
public var topVariable;
public function passone() {
var button: buttonMovie = new buttonMovie();
button.x = 300;
button.y = 400;
button.addEventListener(MouseEvent.CLICK, onButtonClicked);
addChild(button);
topVariable = "Parent variable";
}
function onButtonClicked(e: MouseEvent): void {
trace("This is the variable: " + topVariable);
var myLoader: Loader = new Loader();
var url: URLRequest = new URLRequest("PassVariableTest2.swf");
myLoader.load(url);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
//addChild(myLoader);
function onComplete(e: Event): void {
topVariable = "Parent variable";
addChild(myLoader);
}
}
}
}
Here is the code for the swf the parent calls.
package scripts {
import flash.display.MovieClip;
import flash.text.TextField;
import flash.events.Event;
public class passtwo extends MovieClip {
var topVariable
public function passtwo() {
//var ChildVar = MovieClip(parent.parent).topVariable;
trace("This is being called");
trace("The answer should follow: " +MovieClip(this.parent.parent).topVariable);
//trace(MovieClip(this.parent));
}
}
}
I have tried several different configurations of the code to access the variable from the parent script.
MovieClip(this.parent.parent).topVariable
MovieClip(parent.parent).topVariable
MovieClip(this.parent.parent.parent).topVariable
MovieClip(this.parent).topVariable
I could really use some help figuring this out. I keep getting Error#1009 Cannot access a property or method of a null object reference.
Using a cast to
MovieClip
really is one of those bad practices you can find all over the internet. It doesn't help with anything except obfuscating the problem even more, because all it basically does is prevent any compile time checks from happening, becauseMovieClip
is adynamic
class.From a design point of view, you do not want your loaded swf file to reach out and try to grab stuff from others.
Instead, define the behaviour in a desirable way. If your class needs a value, create a method so it can be passed to it. I use a set function here, so it can be used like a property.
If you compile this into a .swf file and load it, you cast it to the class and not
MovieClip
. Also, don't nest functions into each other unless you know what you are doing.Also see: http://www.scottgmorgan.com/accessing-document-class-of-externally-loaded-swf-with-as3/