Itamar Marom
Itamar Marom

Reputation: 525

Accessing variables inside embedded swf? (AS2)

Right now I'm working on an AS2 code that needs to:

Here is my code, for now:

    loadMovieNum("player.swf",5);
    delay = function () {
    var first:MovieClip = _root.attachMovie("OnTop","nf",10);
    trace(_root.nf);
    trace(_layer5);
    clearInterval(delayi);
    }

delayi = setInterval(delay, 3000); //3 seconds to let the video load. 

I'm trying to show a drawing above a loaded swf ("OnTop" is the name I gave a Symbol which its type is a MovieClip), but what happens is that the video is showing above everything else, and the trace output is:

_level0.nf
undefined

What am I doing wrong? Why isn't the new MovieClip shown above the loaded one? And, next to that, after I load the SWF, how can I access variables inside its main MovieClip?

Upvotes: 0

Views: 1332

Answers (1)

shanethehat
shanethehat

Reputation: 15570

I would personally do this with MovieClipLoader. Using a timer to assume the load duration is very dangerous as it creates a race condition which users with very slow connections will fail.

This is a simple example using MovieClipLoader and Delegate to keep the scope of the event function local to the rest of your code, just like addEventListener does in AS3. First, the SWF to be loaded, which I have called 'child.swf'. This contains an animation and on frame 1 it defines a string variable called 'hello':

var hello:String = "Hi";

In the parent SWF we will have the loader code, and a library item with an identifier of 'mc1', which will be attached to the stage above the loaded SWF.

//grab Delegate to mimic AS3 event handler scope
import mx.utils.Delegate;
//create container for the loaded SWF
var loadedMC:MovieClip = createEmptyMovieClip("loadedMC",5);
//create the loader (don't cast it though, or you can't directly access the events)
var loader = new MovieClipLoader();
//set up a listener for the load init (called when the first frame of the loaded MC is executed)
loader.onLoadInit = Delegate.create(this, onMovieInit);
//start loading
loader.loadClip("child.swf",loadedMC);
//init handler
function onMovieInit()
{
    //create the next layer from the library
    var firstMC:MovieClip = attachMovie("mc1","newName",10);
    //trace var from loaded mc
    trace(loadedMC.hello); // hi
}

MovieClipLoader calls the onLoadInit function when the target SWF is loaded and the first frame has been processed, meaning that any code on the first frame is now available to the parent SWF. Delegating the call to onLoadInit rather than using a listener object as the official documentation would like you to removes the requirement to use _root within the handler function because the scope of the function has not changed.

Upvotes: 0

Related Questions