1

I'm trying to write a function on a MovieClip, and call it from the root clip. What works fine in ActionScript 3 doesn't seem to be working properly in ActionScript 2.

Frame 1 of the _root MovieClip:

var newMovieClip:MovieClip = _root.attachMovie('Notification', id, 0);
newMovieClip.SetNotificationText("Test text");

Frame 1 of the Notification MovieClip:

function SetNotificationText(inputText : String){
    notificationText.text = inputText;
}

The result is that the MovieClip is created but the text is not changed.

Am I doing this wrong?

Christian Stewart
  • 15,217
  • 20
  • 82
  • 139

1 Answers1

2

To add functions to a MovieClip in AS2, you need to use one of these methods:

  1. Add the method to the prototype of MovieClip:

    MovieClip.prototype.SetNotificationText = function(inputText:String):Void
    {
        if(this["notificationText"] !== undefined)
        {
            // If we're going to use the prototype, at least do some checks
            // to make sure the caller MovieClip has the text field we expect.
            this.notificationText.text = inputText;
        }
    }
    
    newMovieClip.SetNotificationText("Test text");
    
  2. Make the MovieClip and argument of the function:

    function SetNotificationText(mc:MovieClip, inputText:String):Void
    {
        mc.notificationText.text = inputText;
    }
    
    SetNotificationText(newMovieClip, "Test text");
    
  3. Add the method directly to the newly created MovieClip:

    var newMovieClip:MovieClip = _root.attachMovie('Notification', id, 0);
    
    newMovieClip.SetNotificationText(inputText:String):Void
    {
        notificationText.text = inputText;
    }
    
    newMovieClip.SetNotificationText("Test text");
    

Option 2 is best overall - it's the cleanest and avoids overhead of creating a new function for every new MovieClip. It also avoids messing around with the prototype, which at best should be used to add generic methods, like a removeItem() method on Array.

Marty
  • 39,033
  • 19
  • 93
  • 162