mediaquery
mediaquery

Reputation: 117

Adding the same function to multiple buttons in Actionscript 3.0

I am trying to add the same button function to 2 different symbols in Flash. One is the logo and the other is text that I converted to a symbol that will show itself during the end scene.

I don't understand what I am doing wrong, but I am extremely new to Actionscript & Flash.

My code looks like this:

import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.net.navigateToURL;
import flash.net.URLRequest;

myButton, txtButton.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
function onClick(e:MouseEvent):void{
    navigateToURL(new URLRequest("http://www.true.land"), "_blank"); 
}

But I am getting this error:

Attempting to launch and connect to Player using URL C:\Users\Angela\Desktop\ASU\GIT 314\Assignment 7\AngelaRogers_Assignment7.swf [SWF] C:\Users\Angela\Desktop\ASU\GIT 314\Assignment 7\AngelaRogers_Assignment7.swf - 351066 bytes after decompression TypeError: Error #1009: Cannot access a property or method of a null object reference. at Button/frame1()[Button::frame1:7]

Upvotes: 1

Views: 1751

Answers (2)

BadFeelingAboutThis
BadFeelingAboutThis

Reputation: 14406

You can write a shortcut function to do this easily enough. (As pointed out by others, your comma is what is causing the error). This I believe is more what you're after: (especially if you keep adding more buttons).

import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.net.navigateToURL;
import flash.net.URLRequest;

addClick(myButton, txtButton); //you can add as many items as you want as parameters

function addClick(...buttons):void {
    //the ...buttons parameter is known as the '...rest' parameter, and is an array of all the parameters passed to the function
    for each(var btn:Sprite in buttons){ //loop through all the items passed in and add the listener
        btn.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
    }
}

function onClick(e:MouseEvent):void{
    navigateToURL(new URLRequest("http://www.true.land"), "_blank"); 
}

Upvotes: 1

Andrey Popov
Andrey Popov

Reputation: 7510

You must write it twice - once for each button, starting with only it's name: child.addEventListener. There is no shortcut to add the same for two objects at once.

Upvotes: 1

Related Questions