Friday, 21 March 2014

AS3 Accessing parent file variable value from a loaded swf file

Below example illustrates how to access a parent file variables value from a loaded swf file.
Create 2 movies. Name them as parMc.fla and cldMc.fla
Draw some graphic in cldMc.fla file like a star.
Open parMc.fla and write the below code:

// import all the necessary classes
import flash.display.Loader;
import flash.display.LoaderInfo;

// create a menuVal variable. This variables value will be read from the childMc
var menuVal:String = "Introduction";

// create a button symbol and give an instance name enterBtn. Clicking this button will load the childMc
enterBtn.addEventListener(MouseEvent.CLICK, onClick);

// create a my_Loader loader object
var my_Loader:Loader = new Loader();

// onClick function is executed on clicking the enterBtn button symbol. This function loads the child mc.
function onClick(evt:MouseEvent):void
var myRequest:URLRequest = new URLRequest("cldMc.swf");
my_Loader.contentLoaderInfo.addEventListener(Event.COMPLETE, swfIn);

// function on completion of loading. Removes the event listener.
function swfIn(evt:Event):void
my_Loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, swfIn);

Now open chdMc.fla and write the below code:

// import the movieclip class
import flash.display.MovieClip;

// create a mainTimeLine variable with MovieClip datatype. This refers to the main timeline i.e. the stage
var mainTimeLine:MovieClip;

// conditional statement to check if the parent is a Loading the child mc i.e the child movies parent is a loader object
if(parent is Loader)
// we assign the MovieClip parent property to the mainTimeLine variable
mainTimeLine = MovieClip(parent.parent);
// Now when we trace the menuVal variable which is defined in the parent mc we get its value

// we check the value of menuVal variable and if its equal to “Introduction” we reduce the alpha of star movieclip.
if(mainTimeLine.menuVal == "Introduction")
star.alpha = .2;

No comments:

Post a Comment