AS3 - Error - The supplied DisplayObject must be a child
I'm using the following code to display an advertisement in a flash game. It works great except for one small issue. If the startButton function gets called before the ad is displayed I get an error saying:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller. at flash.display::DisplayObjectContainer/removeChild() at VirusDefender/clickStart()[VirusDefender::frame1:17]
There are no errors when the advert is on the stage. I tried wrapping the removeChild in a try catch but that did not work.
Could someone please tell me how to prevent the removeChild line from being called if the ad has not been displayed yet. Sometimes it takes up to 3 seconds for the ad to show so people may click before it gets on the stage.
stop();
//Start Button
startScreen.startButton.addEventListener(MouseEvent.CLICK,clickStart);
function clickStart(event:MouseEvent)
{
sndFire=new fire_sound();
sndFireChannel=sndFire.play();
removeChild(l);
gotoAndStop("play");
}
// Help Button
startScreen.helpButton.addEventListener(MouseEvent.CLICK,clickHelp);
function clickHelp(event:MouseEvent)
{
sndFire=new fire_sound();
sndFireChannel=sndFire.play();
removeChild(l);
gotoAndStop("help");
}
// SMAATO Advertising Code for Start Page
var request:URLRequest = new URLRequest("http://soma.smaato.com/oapi/reqAd.jsp");
var variables:URLVariables = new URLVariables();
variables.adspace = "0";
variables.pub = "0";
variables.devip = "127.0.0.1";
variables.format = "IMG";
variables.adcount = "1";
variables.response = "XML";
request.data = variables;
var loader:URLLoader = new URLLoader();
var l:Loader = new Loader();
loader.addEventListener(Event.COMPLETE, onComplete);
loader.load(request);
function onComplete(e:Event):void
{
var d开发者_JAVA技巧ata:XML = new XML(loader.data as String);
var status:String = data.*::status.toString();
if(status == "success")
{
var ad:XMLList = data.*::ads.*::ad;
var link:String = ad.*::link.toString();
l.load(new URLRequest(link));
addChild(l);
l.x = 135;
l.y = 265;
var clickurl:String = ad.*::action.@target.toString();
l.addEventListener(MouseEvent.CLICK, onAdClick);
}
function onAdClick(e:MouseEvent):void
{
var request:URLRequest = new URLRequest(clickurl);
navigateToURL(request);
}
}
Thanks! Rich
Wrap the line into:
if (l != null && contains(l)) {
removeChild(l);
}
This will check if l
is not null and a child, and only then removes it.
Alternatively, as Loader is a DisplayObject, you can simply add it to the stage before anything else (it need not have finished loading before you can add it to the stage) and remove it when start is pressed, that way you wont have it lingering or popping in later if you do in fact want it gone on press.
精彩评论