Calling button in Action Script 3.0 - actionscript-3
I am trying to make button panel. each button have two type btn_home and btn_home_white I am trying to reach those buttons.It is work if I write for each button their own methods like
btn_home.addEventListener(MouseEvent.MOUSE_OVER,overEffect);
btn_home_white.addEventListener(MouseEvent.MOUSE_OUT,outEffect);
function overEffect(e:MouseEvent)
{
var myTweenHight:Tween = new Tween( btn_home,"height",Bounce.easeOut,25,0,3,true);
var myTweenHight2:Tween = new Tween(btn_home_white,"height",Bounce.easeOut,0,25,3,true);
var myTweenAlpha:Tween = new Tween(btn_home_white,"alpha",Strong.easeOut,0,1,2,true);
}
function outEffect(e:MouseEvent)
{
var myTweenHight:Tween = new Tween btn_home,"height",Bounce.easeOut,0,25,3,true);
var myTweenHight2:Tween = new Tween(btn_home_white,"height",Bounce.easeOut,25,0,3,true);
var myTweenAlpha:Tween = new Tween(btn_home_white,"alpha",Strong.easeOut,1,0,2,true);
}
But I have 10 buttons as btn_buttonname and btn_buttonname_white . I tryed to create Event listener on stage for all.It works for firts type buttons btn_buttonname but How can I get second type buttons? I tryed e.target["_white"] but it does not work .
stage.addEventListener(MouseEvent.MOUSE_OVER , overEffect);
stage.addEventListener(MouseEvent.MOUSE_OUT , outEffect);
function overEffect(e:MouseEvent)
{
var myTweenHight:Tween = new Tween(e.target,"height",Bounce.easeOut,25,0,3,true);
trace("height");
var myTweenHight2:Tween = new Tween(e.target["_white"],"height",Bounce.easeOut,0,25,3,true);
var myTweenAlpha:Tween = new Tween(e.target["_white"],"alpha",Strong.easeOut,0,1,2,true);
}
function outEffect(e:MouseEvent)
{
var myTweenHight:Tween = new Tween(e.target,"height",Bounce.easeOut,0,25,3,true);
var myTweenHight2:Tween = new Tween(e.target["_white"],"height",Bounce.easeOut,25,0,3,true);
var myTweenAlpha:Tween = new Tween(e.target["_white"],"alpha",Strong.easeOut,1,0,2,true);
}
EDIT:
I made it work as Daniel Carvalho sad adding for each buttons event listener.Now it works but if I move out mouse on button to other button previous button does not turn original form .
btn_home.addEventListener(MouseEvent.MOUSE_OVER,overEffect);
btn_home_white.addEventListener(MouseEvent.MOUSE_OUT,outEffect);
btn_contact.addEventListener(MouseEvent.MOUSE_OVER,overEffect);
btn_contact_white.addEventListener(MouseEvent.MOUSE_OUT,outEffect);
btn_menu.addEventListener(MouseEvent.MOUSE_OVER,overEffect);
btn_menu_white.addEventListener(MouseEvent.MOUSE_OUT,outEffect);
btn_restaurant.addEventListener(MouseEvent.MOUSE_OVER,overEffect);
btn_restaurant_white.addEventListener(MouseEvent.MOUSE_OUT,outEffect);
btn_rezervation.addEventListener(MouseEvent.MOUSE_OVER,overEffect);
btn_rezervation_white.addEventListener(MouseEvent.MOUSE_OUT,outEffect);
function overEffect(e:MouseEvent)
{
switch (e.target)
{
case ( btn_home) :
{
var HomeTweenHight:Tween = new Tween(btn_home,"height",Bounce.easeOut,25,0,0.5,true);
var HomeTweenHight2:Tween = new Tween(btn_home_white,"height",Bounce.easeOut,0,25,0.5,true);
var HomeTweenAlpha:Tween = new Tween(btn_home_white,"alpha",Strong.easeOut,0,1,2,true);
break;
};
case ( btn_contact) :
{
var ContactTweenHight:Tween = new Tween(btn_contact,"height",Bounce.easeOut,25,0,0.5,true);
var ContactTweenHight2:Tween = new Tween(btn_contact_white,"height",Bounce.easeOut,0,25,0.5,true);
var ContactTweenAlpha:Tween = new Tween(btn_contact_white,"alpha",Strong.easeOut,0,1,2,true);
break;
};
case ( btn_menu) :
{
var MenuTweenHight:Tween = new Tween(btn_menu,"height",Bounce.easeOut,25,0,0.5,true);
var MenuTweenHight2:Tween = new Tween(btn_menu_white,"height",Bounce.easeOut,0,25,0.5,true);
var MenuTweenAlpha:Tween = new Tween(btn_menu_white,"alpha",Strong.easeOut,0,1,2,true);
break;
};
case ( btn_restaurant) :
{
var RestourantTweenHight:Tween = new Tween(btn_restaurant,"height",Bounce.easeOut,25,0,0.5,true);
var RestourantTweenHight2:Tween = new Tween(btn_restaurant_white,"height",Bounce.easeOut,0,25,0.5,true);
var RestourantTweenAlpha:Tween = new Tween(btn_restaurant_white,"alpha",Strong.easeOut,0,1,2,true);
break;
};
case (btn_rezervation) :
{
var RezervationTweenHight:Tween = new Tween(btn_rezervation,"height",Bounce.easeOut,25,0,0.5,true);
var RezervationTweenHight2:Tween = new Tween(btn_rezervation_white,"height",Bounce.easeOut,0,25,0.5,true);
var RezervationTweenAlpha:Tween = new Tween(btn_rezervation_white,"alpha",Strong.easeOut,0,1,2,true);
break;
}
}
};
function outEffect(e:MouseEvent)
{
switch (e.target)
{
case (btn_home_white) :
{
var HomeTweenHight:Tween = new Tween(btn_home,"height",Bounce.easeOut,0,25,0.5,true);
var HomeTweenHight2:Tween = new Tween(btn_home_white,"height",Bounce.easeOut,25,0,0.5,true);
var HomeTweenAlpha:Tween = new Tween(btn_home_white,"alpha",Strong.easeOut,1,0,2,true);
break;
};
case (btn_contact_white) :
{
var ContactTweenHight:Tween = new Tween(btn_contact,"height",Bounce.easeOut,0,25,0.5,true);
var ContactTweenHight2:Tween = new Tween(btn_contact_white,"height",Bounce.easeOut,25,0,0.5,true);
var ContactTweenAlpha:Tween = new Tween(btn_contact_white,"alpha",Strong.easeOut,1,0,2,true);
break;
}
case (btn_menu_white) :
{
var MenuTweenHight:Tween = new Tween(btn_menu,"height",Bounce.easeOut,0,25,0.5,true);
var MenuTweenHight2:Tween = new Tween(btn_menu_white,"height",Bounce.easeOut,25,0,0.5,true);
var MenuTweenAlpha:Tween = new Tween(btn_menu_white,"alpha",Strong.easeOut,1,0,2,true);
break;
};
case (btn_restaurant_white) :
{
var RestourantTweenHight:Tween = new Tween(btn_restaurant,"height",Bounce.easeOut,0,25,0.5,true);
var RestourantTweenHight2:Tween = new Tween(btn_restaurant_white,"height",Bounce.easeOut,25,0,0.5,true);
var RestourantTweenAlpha:Tween = new Tween(btn_restaurant_white,"alpha",Strong.easeOut,1,0,2,true);
break;
};
case (btn_rezervation_white) :
{
var RezervationTweenHight:Tween = new Tween(btn_rezervation,"height",Bounce.easeOut,0,25,0.5,true);
var RezervationTweenHight2:Tween = new Tween(btn_rezervation_white,"height",Bounce.easeOut,25,0,0.5,true);
var RezervationTweenAlpha:Tween = new Tween(btn_rezervation_white,"alpha",Strong.easeOut,1,0,2,true);
break;
};
}
};
Your e.target should work, though you don't (as far as I can see) need the [_"white"] after e.target for your _white buttons. The reason the e.targets aren't working is because you're just adding event listeners to the stage, and not the individual buttons.
I see two choices (perhaps there are others): manually go through writing event listeners for each button, or put all the buttons that will use the overEffect function into one Array, and all the buttons using the outEffect function into another Array.
Then create two for loops, and go through those Arrays adding the event listeners to each child of the array. Your e.target code should work at that point.
Let me know if you have any trouble with that, hope it helps.
debu
Here is a quick example that may help you:
http://wonderfl.net/c/vhay
function createButton():MovieClip{
var button:MovieClip=new MovieClip();
var stateA:Shape=new Shape();
var g:Graphics = stateA.graphics;
g.beginFill(0xFF0000);
g.drawRect(0, 0, 10, 10);
g.endFill();
button["stateA"] = stateA;
button.addChild(stateA);
var stateB:Shape=new Shape();
g = stateB.graphics;
g.beginFill(0x00FF00);
g.drawRect(0, 0, 10, 10);
g.endFill();
button["stateB"] = stateB;
button.addChild(stateB);
stateB.visible=false;
return button;
}
var nbButtons:int=10;
var buttons:Array=[];
var selectButton:MovieClip;
for (var i : int = 0;i < nbButtons; i++) {
var button:MovieClip=createButton();
addChild(button);
button.y=10;
button.x=i*12+10;
addChild(button);
buttons.push(button);
setUpButton(button);
}
function setUpButton(button:MovieClip):void {
button.buttonMode=true;
button.addEventListener(MouseEvent.ROLL_OVER, buttonRollOver);
button.addEventListener(MouseEvent.ROLL_OUT, buttonRollOut);
button.addEventListener(MouseEvent.CLICK, buttonClick);
}
function buttonClick(e:Event):void{
switchButtonStateToNotSelected();
switchButtonStateToSelected(e.currentTarget as MovieClip);
}
function switchButtonStateToSelected(button:MovieClip):void{
button.buttonMode=true;
button.removeEventListener(MouseEvent.ROLL_OVER, buttonRollOver);
button.removeEventListener(MouseEvent.ROLL_OUT, buttonRollOut);
button.removeEventListener(MouseEvent.CLICK, buttonClick);
button["stateA"]["visible"]=false;
button["stateB"]["visible"]=true;
selectButton=button;
}
function switchButtonStateToNotSelected():void{
if(selectButton) {
setUpButton(selectButton);
selectButton["stateA"]["visible"]=true;
selectButton["stateB"]["visible"]=false;
selectButton=null;
}
}
function buttonRollOver(e:Event):void{
e.currentTarget["stateA"]["visible"]=false;
e.currentTarget["stateB"]["visible"]=true;
}
function buttonRollOut(e:Event):void{
e.currentTarget["stateA"]["visible"]=true;
e.currentTarget["stateB"]["visible"]=false;
}
Related
New array for music symbols
I have background musics from the library, any ideas how to solve this code by clicking the button to change it? var BeachBall: CrashBash_BeachBall = new CrashBash_BeachBall(); var BrickDive: LEGOIsland2_BrickDive = new LEGOIsland2_BrickDive(); var BloocheepOcean: MarioHoops_BloocheepOcean = new MarioHoops_BloocheepOcean(); var Underwater: MarioTeachesTyping2_Underwater = new MarioTeachesTyping2_Underwater(); var UnderPressure: CrashBandicootNST_UnderPressure = new CrashBandicootNST_UnderPressure(); var CalmWaters: DireDireDocks_CalmWaters = new DireDireDocks_CalmWaters(); var Level1: TreasureCove_Level1 = new TreasureCove_Level1(); var Level2: TreasureCove_Level2 = new TreasureCove_Level2(); var Level3: TreasureCove_Level3 = new TreasureCove_Level3(); var music: Array = new Array(CalmWaters, BloocheepOcean, UnderPressure, Underwater, BeachBall, BrickDive, Level1, Level2, Level3); // Changing the Background Music music_btn.addEventListener(MouseEvent.CLICK, on_pressMusic); music[Math.floor(Math.random()*music.length)].play(); if(!sound) { sound_channel = CalmWaters.play(0, int.MAX_VALUE); sound_channel.soundTransform = new SoundTransform(0.4); } function on_pressMusic(event: MouseEvent): void { /* var random: int = int(Math.random() * sounds[0].length); play_music(sounds[0][random]); var sMusic:Button = new Button(); sMusic.play(); */ if (is_Playing == true) //# if music is already playing { music_player.stop(); } musicNum = Math.floor(Math.random() * (musicList.length-1)); music_object = new (musicList[musicNum]); audioTime = 0; //# seconds to start from within track music_player = music_object.play(audioTime); is_Playing = true; } Error: TypeError: Error #1007: Instantiation attempted on a non-constructor. at BlowfishPong_fla::MainTimeline/on_pressMusic()[BlowfishPong_fla.MainTimeline::frame27:205] All of the codes are updated. any ideas how to solve and fix this for their future coding.
Try something like this: var BeachBall: CrashBash_BeachBall = new CrashBash_BeachBall(); var BrickDive: LEGOIsland2_BrickDive = new LEGOIsland2_BrickDive(); var BloocheepOcean: MarioHoops_BloocheepOcean = new MarioHoops_BloocheepOcean(); var CalmWaters: DireDireDocks_CalmWaters = new DireDireDocks_CalmWaters(); var Level1: TreasureCove_Level1 = new TreasureCove_Level1(); var Level2: TreasureCove_Level2 = new TreasureCove_Level2(); var Level3: TreasureCove_Level3 = new TreasureCove_Level3(); var Underwater: MarioTeachesTyping2_Underwater = new MarioTeachesTyping2_Underwater(); var UnderPressure: CrashBandicootNST_UnderPressure = new CrashBandicootNST_UnderPressure(); var myNum :uint = 0; var audioTime :uint = 0; var music_object :Sound; var music_player :SoundChannel = new SoundChannel(); var is_Playing :Boolean = false; var music_list :Array = new Array(); music_list = [ BeachBall, BrickDive, BloocheepOcean, CalmWaters, Level1, Level2, Level3, Underwater, UnderPressure ]; //# Changing the Background Music music_btn.addEventListener(MouseEvent.CLICK, on_pressMusic); function on_pressMusic (event:MouseEvent) : void { if ( is_Playing == true ) //# if music is already playing { music_player.stop(); } myNum = Math.floor( Math.random() * (music_list.length-1) ); music_object = new ( music_list[ myNum ] ); audioTime = 0; //# seconds to start from within track music_player = music_object.play( audioTime ); is_Playing = true; }
Match two strings from a text file and user input? (AS3)
I was able to load a text file in a Flash file, but I am unable to match two strings from a text file and the user input. The purpose of this AS3 code: to match the text file and user input, and if it matches, the score will increase by 1. Else, the score will increase by 0. Here is my code: var uScore :Number = 0; stop(); var textLoader:URLLoader = new URLLoader(); var textURLRequest:URLRequest = new URLRequest("q1.txt"); textLoader.addEventListener(Event.COMPLETE, completeHandler); function completeHandler(event:Event):void { var textData:String = new String(textLoader.data); dy1.text = textData; } textLoader.load(textURLRequest); function goURL(event:MouseEvent):void { var textLoader2:URLLoader = new URLLoader(); var textURLRequest2:URLRequest = new URLRequest("answer1.txt"); var textData2:String = new String(textLoader2.data); var name1 = trace(textData2); textLoader2.load(textURLRequest2); var myURL = url1.text; if(myURL == name1){ uScore += 1; uScoreURL.text = uScore+""; nextFrame(); } else{ uScore+=0; uScoreURL.text = uScore+""; nextFrame(); } } trace(uScore);
You code has a strange assignment: var name1 = trace(textData2); replace it with var name1 =textData2; it should work then if there isn't a bug in some other place. And you don't need to uScore+=0;. Just delete it.
I checked out your code, you were doing a few things out of order - here is the revised code that should get you where you need to be var uScore :Number = 0; stop(); var textLoader:URLLoader = new URLLoader(); var textURLRequest:URLRequest = new URLRequest("q1.txt"); textLoader.addEventListener(Event.COMPLETE, completeHandler); function completeHandler(event:Event):void { var textData:String = new String(textLoader.data); dy1.text = textData; } textLoader.load(textURLRequest); btn.addEventListener(MouseEvent.CLICK,getNumber); var textLoader2:URLLoader = new URLLoader(); textLoader2.addEventListener(Event.COMPLETE, completeHandler2); function completeHandler2(event:Event):void { var textData2:String = new String(textLoader2.data); var name1 = textData2; trace(name1); var myURL = url1.text; if(myURL == name1){ uScore += 1; uScoreURL.text = uScore+""; nextFrame(); } else{ uScore+=0; uScoreURL.text = uScore+""; nextFrame(); } } function getNumber(event:MouseEvent){ var textURLRequest2:URLRequest = new URLRequest("answer1.txt"); textLoader2.load(textURLRequest2); } trace(uScore); The only thing that I really added that you didn't have is a button with the variable name btn to check the answer - you can rework that to however you want to check for the answer.
Best way of passing values from a button with as3 event
I develop my own way of doing this simple task. However, I'm now wondering if there is a better way to do it. The buttons: var menuBtnEscrit:MovieClip = new MovieClip(); var mbe:btnEscritorio = new btnEscritorio(); menuBtnEscrit.addChild(mbe); menuBtnEscrit.val = "escrit"; menuBtnEscrit.x = 80; menuBtnEscrit.addEventListener(MouseEvent.CLICK, novoCont); dMenu.addChild(menuBtnEscrit); var menuBtnPublic:MovieClip = new MovieClip(); var mbp:btnPublic = new btnPublic(); menuBtnPublic.addChild(mbp); menuBtnPublic.val = "public"; menuBtnPublic.x = 244; menuBtnPublic.addEventListener(MouseEvent.CLICK, novoCont); dMenu.addChild(menuBtnPublic); And I can keep going, or create buttons trough some algorithm, and put more properties and take advantage of a MovieClip. The handler: private function novoCont(e=null){ if(e!=null) selecCont = new String(e.target.parent.val); clearDisplay(dSubMenu); clearDisplay(dConteudo); var func:String = "cont_"+selecCont; this[func](); } As you can see, there is some common task for all buttons. If I click the first button, it will call cont_escrit() function. This mechanics works, but it is the best practice? Is there a way of optimize it?
public class BaseButton extends Button { private var _func:Function; public function get handler():Function { return _func; } public function set handler(value:Function):void { _func = value; } } So hero you can create mbe like this mbe = new BaseButton (); mbe.hanler = cont_escrit; The event hanler would be private function novoCont(e=null){ if(e!=null) { var selecContent:BaseButton = e.targe as BaseButton ; var handler:Function = selecContent.handler; handler(); } } Here is an example. var menuBtnEscrit:MovieClip = new MovieClip(); var mbe:btnEscritorio = new btnEscritorio(); menuBtnEscrit.addChild(mbe); //menuBtnEscrit.val = "escrit"; menuBtnEscrit.func = this.cont_escrit; menuBtnEscrit.x = 80; menuBtnEscrit.addEventListener(MouseEvent.CLICK, novoCont); private function novoCont(e=null){ if(e!=null) { var mc:MovieClip = e.target as MovieClip; var func:Function = mc.func; func(); } clearDisplay(dSubMenu); clearDisplay(dConteudo); }
#2007: Parameter format must be non-null?
i have a problem with my as3 code, i try to link a movie clip to different scene (quiz scene). so,i have 2 quiz in total, first quiz is using external script (as) And the second quiz have the same script like first quiz, but i placed the action script inside fla. and it had different xml. but then this error message appeared: TypeError: Error #2007: Parameter format must be non-null. at flash.text::TextField/set defaultTextFormat() at hiragana/createText()[E:\flash\!!!! FLASH JADI\PAK ASHAR FIX\hiragana.as:80] at hiragana/kuisdua()[hiragana::frame209:48] at hiragana/frame209()[hiragana::frame209:249] this is the code: // creates a text field public function createText(text:String, tf:TextFormat, s:Sprite, x,y: Number, width:Number): TextField { var tField:TextField = new TextField(); tField.x = x; tField.y = y; tField.width = width; tField.defaultTextFormat = tf; //looks like this is the source of problem (-.-) tField.selectable = false; tField.multiline = true; tField.wordWrap = true; if (tf.align == "left") { tField.autoSize = TextFieldAutoSize.LEFT; } else { tField.autoSize = TextFieldAutoSize.CENTER; } tField.text = text; s.addChild(tField); return tField; } and this is the ettire code import flash.display.*; import flash.text.*; import flash.events.*; import flash.net.URLLoader; import flash.net.URLRequest; ///*public class*/ kuisduaa extends MovieClip { // question data /*private*/ var dataXML2:XML; // text formats /*private*/ var questionFormat2:TextFormat; /*private*/ var answerFormat2:TextFormat; /*private*/ var scoreFormat2:TextFormat; // text fields /*private*/ var messageField2:TextField; /*private*/ var questionField2:TextField; /*private*/ var scoreField2:TextField; // sprites and objects /*private*/ var gameSprite2:Sprite; /*private*/ var questionSprite2:Sprite; /*private*/ var answerSprites2:Sprite; /*private*/ var gameButton2:GameButton; // game state variables /*private*/ var questionNum2:int; /*private*/ var correctAnswer2:String; /*private*/ var numQuestionsAsked2:int; /*private*/ var numCorrect2:int; /*private*/ var answers2:Array; /*public*/ function kuisdua() { // create game sprite gameSprite2 = new Sprite(); addChild(gameSprite2); // set text formats questionFormat2 = new TextFormat("Arial",80,0xffffff,true,false,false,null,null,"center"); answerFormat2 = new TextFormat("Arial",50,0xffffff,true,false,false,null,null,"left"); scoreFormat2 = new TextFormat("Arial",30,0xffffff,true,false,false,null,null,"center"); // create score field and starting message text scoreField2 = createText("",scoreFormat,gameSprite,-30,550,550); messageField2 = createText("Loading Questions...",questionFormat,gameSprite,0,50,550); // set up game state and load questions questionNum2 = 0; numQuestionsAsked2 = 0; numCorrect2 = 0; showGameScore2(); xmlImport2(); } // start loading of questions /*public*/ function xmlImport2() { var xmlURL:URLRequest = new URLRequest("kuis2.xml"); var xmlLoader:URLLoader = new URLLoader(xmlURL); xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded); } // questions loaded /*public*/ function xmlLoaded2(event:Event) { dataXML = XML(event.target.data); gameSprite.removeChild(messageField); messageField = createText("Tap Untuk Memulai",scoreFormat,gameSprite,-10,250,500); showGameButton("mulai"); } // creates a text field /*public*/ function createText2(text:String, tf:TextFormat, s:Sprite, x,y: Number, width:Number): TextField { var tField2:TextField = new TextField(); tField2.x = x; tField2.y = y; tField2.width = width; tField2.defaultTextFormat = tf; tField2.selectable = false; tField2.multiline = true; tField2.wordWrap = true; if (tf.align == "left") { tField2.autoSize = TextFieldAutoSize.LEFT; } else { tField2.autoSize = TextFieldAutoSize.CENTER; } tField2.text = text; s.addChild(tField2); return tField2; } // updates the score /*public*/ function showGameScore2() { scoreField2.text = "Soal: "+numQuestionsAsked2+" Benar: "+numCorrect2; } // ask player if they are ready for next question /*public*/ function showGameButton2(buttonLabel:String) { gameButton = new GameButton(); gameButton.label.text = buttonLabel; gameButton.x = 240; gameButton.y = 480; gameSprite2.addChild(gameButton); gameButton.addEventListener(MouseEvent.CLICK,pressedGameButton2); } // player is ready /*public*/ function pressedGameButton2(event:MouseEvent) { // clean up question if (questionSprite2 != null) { gameSprite2.removeChild(questionSprite2); } // remove button and message gameSprite2.removeChild(gameButton); gameSprite2.removeChild(messageField2); // ask the next question if (questionNum >= dataXML.child("*").length()) { gotoAndStop(6); } else { askQuestion2(); } } // set up the question /*public*/ function askQuestion2() { // prepare new question sprite questionSprite2 = new Sprite(); gameSprite2.addChild(questionSprite2); // create text field for question var question2:String = dataXML.item[questionNum].question2; if (dataXML.item[questionNum].question.#type == "text") { questionField2 = createText(question2,questionFormat2,questionSprite2,50,150,300); } else { var questionLoader2:Loader = new Loader(); var questionRequest2:URLRequest = new URLRequest("triviaimages/"+question2); questionLoader2.load(questionRequest2); questionLoader2.y = 150; questionLoader2.x = 180; questionSprite2.addChild(questionLoader2); } // create sprite for answers, get correct answer and shuffle all correctAnswer2 = dataXML.item[questionNum2].answers.answer[0]; answers2 = shuffleAnswers(dataXML.item[questionNum2].answers); // put each answer into a new sprite with a icon answerSprites2 = new Sprite(); var xpos:int = 0; var ypos:int = 0; for(var i:int=0;i<answers2.length;i++) { var answerSprite2:Sprite = new Sprite(); if (answers2[i].type == "text") { var answerField2:TextField = createText(answers2[i].value,answerFormat2,answerSprite2,30,-35,200); } else { var answerLoader2:Loader = new Loader(); var answerRequest2:URLRequest = new URLRequest("triviaimages/"+answers2[i].value); answerLoader2.load(answerRequest2); answerLoader2.y = -22; answerLoader2.x = 25; answerSprite2.addChild(answerLoader2); } var letter:String = String.fromCharCode(65+i); // A-D var circle:Circle = new Circle(); // from Library circle.letter.text = letter; circle.answer = answers[i].value; answerSprite2.x = 100+xpos*250; answerSprite2.y = 350+ypos*100; xpos++ if (xpos > 1) { xpos = 0; ypos += 1; } answerSprite2.addChild(circle); answerSprite2.addEventListener(MouseEvent.CLICK,clickAnswer); // make it a button // set a larger click area answerSprite2.graphics.beginFill(0x000000,0); answerSprite2.graphics.drawRect(-50, 0, 200, 80); answerSprites2.addChild(answerSprite2); } questionSprite2.addChild(answerSprites2); } // take all the answers and shuffle them into an array /*public*/ function shuffleAnswers2(answers:XMLList) { var shuffledAnswers2:Array = new Array(); while (answers2.child("*").length() > 0) { var r:int = Math.floor(Math.random()*answers.child("*").length()); shuffledAnswers2.push({type: answers2.answer[r].#type, value: answers2.answer[r]}); delete answers2.answer[r]; } return shuffledAnswers2; } // player selects an answer /*public*/ function clickAnswer2(event:MouseEvent) { // get selected answer text, and compare var selectedAnswer2 = event.currentTarget.getChildAt(1).answer; if (selectedAnswer2 == correctAnswer2) { numCorrect++; messageField2 = createText("Hai, kamu benar ! ",scoreFormat2,gameSprite2,-30,280,550); } else { messageField2 = createText("Iie, Jawabanmu Salah, yang benar adalah:",scoreFormat2,gameSprite2,53,280,370); } finishQuestion(); } /*public*/ function finishQuestion2() { // remove all but the correct answer for(var i:int=0;i<4;i++) { answerSprites2.getChildAt(i).removeEventListener(MouseEvent.CLICK,clickAnswer); if (answers2[i].value != correctAnswer2) { answerSprites2.getChildAt(i).visible = false; } else { answerSprites2.getChildAt(i).x = 200; answerSprites2.getChildAt(i).y = 400; } } // next question questionNum2++; numQuestionsAsked2++; showGameScore2(); showGameButton2("Lanjutkan"); } // clean up sprites /*public*/ function CleanUp2() { removeChild(gameSprite); gameSprite2 = null; questionSprite2 = null; answerSprites2 = null; dataXML2 = null; } the first quiz played perfectly with that code, and i have no clue why this error appeared, i'm beginner in as3 so i'm still lack in many ways, can anyone help me,? i really apreciate it.. :)
Are you sure that you're parsing a non-null TextFormat instance as the second argument of createText()? The error means that you're supplying a null value for tf:TextFormat.
Unless I am missing something, your issue is here: messageField2 = createText("Loading Questions...",questionFormat,gameSprite,0,50,550); & messageField = createText("Tap Untuk Memulai",scoreFormat,gameSprite,-10,250,500); I see questionFormat2 and scoreFormat2 are instantiated, but I never see a questionFormat or scoreFormat. Your error says that the defaultTextFormat (or TextFormat supplied using setTextFormat(), for future reference), cannot be null. Null means that the object has not been instantiated/created yet. questionFormat and scoreFormat are never instantiated. Hell, their variables do not even exist. If you were using a proper development IDE (FlashBuilder, FlashDevelop, etc), you'd never be able to compile this code. Switch those two lines to use the correct formats and you should be fine.
AS3 Adobe AIR: Return xml string
I'm working in Flash CS6 with Adobe AIR 3.3 (for iOS) and having trouble returning an XML string to a textField. It is tracing the proper information, and I've tried a few ways to return the trace but can't seem to quite get it... Here is my most recent try. Any suggestions? Thanks in advance. var myLoader:URLLoader = new URLLoader(); myLoader.load(new URLRequest("http://www.someURL.php")); //php file that echos xml myLoader.addEventListener(Event.COMPLETE, init); var fadedText:TextField; var touchList:TouchList; var textOutput:TextField; var animateLeft:Tween; var listArray:Array; var item:TouchListItemRenderer; var theXML:XML; var days:Array = new Array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"); var daySelected; var businessNameArray:Array = new Array(); var businessLogoArray:Array = new Array(); var businessAddress:Array = new Array(); var distanceArrayDisplay:Array = new Array(); var distanceArrayCount = 0; function init(e:Event = null):void { trace(myLoader.data); theXML = new XML(e.target.data); theXML.ignoreWhitespace = true; myLoader.close(); // add our list and listener var itemSizeCalculator = stage.stageHeight / 6; touchList = new TouchList(stage.stageWidth, stage.stageHeight-itemSizeCalculator); touchList.addEventListener(ListItemEvent.ITEM_SELECTED, handlelistItemSelected); addChild(touchList); touchList.x = stage.stageWidth; // Fill our list with item rendreres that extend ITouchListRenderer. for(var i:int = 0; i < theXML.food.length(); i++) { if(theXML.food[i].monday != "un") { item = new TouchListItemRenderer(); item.index = i; item.data = theXML.food[i].business; item.name = theXML.food[i].business; item.addEventListener(MouseEvent.CLICK, itemWasClicked); item.itemHeight = itemSizeCalculator; businessNameArray[i]= theXML.food[i].business; businessLogoArray[i]=("http://www.logosURL.com/"+theXML.food[i].logo); businessAddress[i]= theXML.food[i].address; var fadedTextFormat:TextFormat = new TextFormat(); fadedTextFormat.bold = true; fadedTextFormat.color = 0x999999; fadedTextFormat.size = 14; fadedTextFormat.font = "Helvetica"; fadedText = new TextField(); fadedText.height = 30; fadedText.mouseEnabled = false; fadedText.defaultTextFormat = fadedTextFormat; item.addChild(fadedText); fadedText.x = 75; fadedText.y = 10; distanceArrayDisplay.push(fadedText); var distanceLoader:URLLoader = new URLLoader(); distanceLoader.load(new URLRequest("http://maps.googleapis.com&origins=someAddress&destinations="+businessAddress[i]+"&mode=walking&language=en-en&sensor=false")); distanceLoader.addEventListener(Event.COMPLETE, distanceCalculated); var logoLoader:Loader = new Loader(); item.addChild(logoLoader); var logoURL:URLRequest = new URLRequest("http://www.myLogos.com/"+theXML.food[i].logo); logoLoader.load(logoURL); logoLoader.scaleX = .4; logoLoader.scaleY = .4; logoLoader.y = logoLoader.y + 5; logoLoader.mouseEnabled = false; var arrowGraphic:rightArrow = new rightArrow(); item.addChild(arrowGraphic); arrowGraphic.x = stage.stageWidth - 5; arrowGraphic.y = item.height/2; touchList.addListItem(item); } } } function distanceCalculated(e:Event) { // trace(e.currentTarget.data); var distanceXML:XML = new XML(e.target.data); distanceXML.ignoreWhitespace = true; var returnVar:String = (distanceXML.row.element.distance.text); distanceArrayDisplay[distanceArrayCount].text = returnVar; trace(returnVar); distanceArrayCount++; }
I am guessing that you are correctly reading the first XML, and that XML has a list of URLs that you want to load and then display some info from those on TextFields. Without knowing the structure of that XML I can't suggest you any working code, but I can point you on the right direction. For more info on reading/iterating XML on flash as3, please read: http://www.kirupa.com/developer/flashcs3/using_xml_as3_pg1.htm //iterator var var xml_read:uint=0; //array of textfields for reference var array_textFields:Array; //config XML complete function init(e:Event = null):void { array_textFields = new Array(); theXML = new XML(e.target.data); theXML.ignoreWhitespace = true; //this depends on the XML structure, please look at the article I linked //for more info on how to iterate an XML var i:uint=0; for(someUrl in theXML..url) { var fadedText:TextField = new TextField(); //you should place each Textfield on different coord, otherwise //they will all stack on top of each other and you will only see one //for example: fadedText.y = (fadedText.height+10)*i; item.addChild(fadedText); array_textFields.push(fadedText); var distanceLoader:URLLoader = new URLLoader(); distanceLoader.load(new URLRequest(someUrl)); distanceLoader.addEventListener(Event.COMPLETE, distanceCalculated); i++; } } function distanceCalculated(e:Event):void { var distanceXML:XML = new XML(e.target.data); distanceXML.ignoreWhitespace = true; //retrieve information var returnVar:String = (distanceXML.row.element.distance.text); //set to textfield TextField(array_textFields[xml_read]) = returnVar; //increase iterator xml_read++; } Please bear in mind that in ActionScript3, all network I/O is asynchronous. Usually EventListener functions don't return any value because you don't know when the data is ready. What you do is store a reference to where you want the data to go (in your case, a TextField variable) when the EventListener function is called asynchronously.