AS3 Linking-Loading Another Swf File - actionscript-3

i made catching game and i have the swf file. In another flash project, i want to call that swf. I created a button and wrote the codes below.
btnn.addEventListener(MouseEvent.CLICK, fl_ClickToLoadUnloadSWF_4);
import fl.display.ProLoader;
var fl_ProLoader_4:ProLoader;
var fl_ToLoad_4:Boolean = true;
function fl_ClickToLoadUnloadSWF_4(event:MouseEvent):void
{
if(fl_ToLoad_4)
{
fl_ProLoader_4 = new ProLoader();
fl_ProLoader_4.load(new URLRequest("CathingGame.swf"));
addChild(fl_ProLoader_4);
}
else
{
fl_ProLoader_4.unload();
removeChild(fl_ProLoader_4);
fl_ProLoader_4 = null;
}
fl_ToLoad_4 = !fl_ToLoad_4;
}
But when i click the button, i have the error below. What could be the possible solutions? I think i have this error because in the catching game, my fla and actionscript are in different file. I mean i use external .as file. Not in the fla file.
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at CatchingGame()

Your loading code is fine, but exception is originated from the CatchingGame code, so that's not possible to say for sure what's the reason.
But, if (as I guess) your game works fine when it's launched without preloading the most probable reason for null object reference in that case is too earlier accessing to stage property from the game. Try to move game initiation logic to ADDED_TO_STAGE event handler like in example below:
public function MyGame()
{
if (stage)
{
init();
}
else
{
addEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
}
}
private function onAddedToStage( event:Event ):void
{
removeEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
init();
}
private function init():void
{
//place init logic here
}
If my guess wrong, add more code from CatchingGame swf.

Related

Avoid null object reference errors in code inside the child SWF

I'm creating a global loader that loads different SWFs.
I don't have access to the child SWFs code.
I'm trying to avoid null object reference errors in code inside the child SWF that may reference "stage" etc.
I've added all the possible event listeners, added try/catch, tried all the applicationDomains and LoaderContexts permutations. for example:
applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
var con:LoaderContext = new LoaderContext(false, applicationDomain );
con.allowCodeImport = true;
var _loader:Loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoad);
_loader.load( new URLRequest(fileName + ".swf"), con);
I just can't catch the error or disable/remove the code from such a SWF.
for example, the following Main class:
package {
import flash.display.MovieClip;
public class Main extends MovieClip {
public function Main() {
var h = this.stage.stageHeight;
trace(h);
}
}
}
will crush any SWF that will try to load it as part of another SWF.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main()
Any help with catching the Error, disabling/removing the code or any other idea will be much appreciated.
Thanks.
Do you have access to the code in the child swf files? If so, you can do something like this:
package {
import flash.display.MovieClip;
public class Main extends MovieClip {
public function Main() {
if (stage) {
init();
}
else {
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
public function init(evt:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
// You can now access the stage here
}
}
}
This will hold off initializing the child object until the stage reference is set. For all child objects the constructor will be called first before the stage is set, so you can't rely on it being there in the constructor.

added MovieClip to stageChild and rootChild but still not visible, modifying index doesn't work as well

I am new to action script and working with .fla file add an indicator to my audio recorder,
The following is the code for my Main class initializer, which earlier used to record sound with no mic feedback, then I decided to mess with it by adding a movieClip to display feedback
public function Main()
{
Security.allowDomain("*");
try {
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
drawStartPlayButton();
drawStopPlayButton();
drawStartButton();
drawStopButton();
this.micIndicator = new ActivityBar(this.stage, this);
this.setChildIndex(this.micIndicator, 0);
recorder.thisStage = this.stage;
recorder.thisActivity = this.micIndicator;
start_play_sound_button.addEventListener(MouseEvent.CLICK, onPrepare);
addChild(start_play_sound_button);
addChild(micIndicator);
start_record_button.addEventListener(MouseEvent.CLICK, onStart);
addChild(start_record_button);
stop_record_button.addEventListener(MouseEvent.CLICK, onStop);
addChild(stop_record_button);
recorder.thisActivity = micIndicator;
micIndicator.stop();
micIndicator.x = 0;
micIndicator.y = 0;
this.addChild(micIndicator);
trace("added to stage");
if (checkJavaScriptReady()) {
} else {
var readyTimer:Timer = new Timer(100, 0);
readyTimer.addEventListener(TimerEvent.TIMER, timerHandler);
readyTimer.start();
}
} catch (error:SecurityError) {
//ExternalInterface.call("sendToJavaScript", error.message);
} catch (error:Error) {
//ExternalInterface.call("sendToJavaScript", error.message);
}
}
Now my ActivityBar is extends MovieClip
package org.bytearray.micrecorder {
public class ActivityBar extends MovieClip {
public function ActivityBar(stage:Stage, parent:Sprite) {
super();
this.name = "micIndicator";
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.addChild(this);
}
public function onAddedToStage(e:Event):void {
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
this.width = 150;
this.height = 30;
this.gotoAndStop(1);
}
public function goToFrame(e:Event):void {
trace("calling goToFrame");
}
}
}
The ActivityBar is supposed display a .fla movie file with 58 frames in it.
The buttons are drawn in the current state, but activity despite being initialized and added to stage, doesn't display
I am using FlashDevelop with flex SDK to develop this code
The buttons are drawn, but when I setChildIndex(micIndicator) higher, the output is blank
There is error in playing MovieClip standalone,
The height and width of movie wont change even in constructer
Why can't I display MovieClip, when I see the published swf of .fla file, I can see that ActivityBar is included in classes, so Its linked correctly.
What is the right way to do this?
Is there some tutorial I can refer too,
this is my first action script project.
public function stage_EnterFrame(e:Event)
{
var num:Number = _microphone.activityLevel;
trace("in the stage_entrance");
trace(thisStage.getChildByName("micIndicator"));
trace("===========================");
thisActivity.play();
if (thisStage.getChildByName("micIndicator") == null) {
trace("no recorder movie clip");
thisStage.addChild(thisActivity);
}
trace(thisActivity.currentFrame);
thisActivity.gotoAndStop(uint((num/100)*29));
}
The function above goes to frame corresponding to mic level.
There is nothing wrong with the linkage. Will try to hint you...
public function ActivityBar(stage:Stage, parent:Sprite) {
super();
this.name = "micIndicator";
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.addChild(this); //<-----
}
Q: Where are you adding the child to?
A: stage
this.micIndicator = new ActivityBar(this.stage, this);
this.setChildIndex(this.micIndicator, 0);
Q: What object are you calling setChildIndex() on?
A: instance of Main
Q: Is stage the same as the instance of Main?
A: No
Q: Can you use instance_of_main.setChildIndex(...) and expect it will rearrange the index of the child that belongs to stage?
A: No
Q: Aaaaand, do you know why you are not thrown a runtime error there? Despite the fact that you should see one as you are calling setChildIndex with a child that is not the child of main?
A: Cos you are using a try/catch block - it has ABSOLUTELY no place there as there is no code there that could throw you an error that you should catch.
Got it? ;)
Also bytearray.org is not your domain, why would you use it as a package name?
PS: Your main (document) class should extend either Sprite or MovieClip.

TypeError: Error #1009 with loading external SWF file

I was making 3D File Viewer in Flash Player with AS3.0
and i found AWD Viewer from Away3D Example File.
(http://awaytools.com/awaybuilder/tutorial-01/AwayBuilderTutorial01_SampleFiles.zip)
it works fine.
and i loaded it in my 'Main' swf file. but it's not work. it kept showing error to me.
error message is below
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at AWDViewer/initEngine()[C:\Users\wintec\Desktop\Flash3DViewer\source\AWDViewer.as:74]
at AWDViewer/init()[C:\Users\wintec\Desktop\Flash3DViewer\source\AWDViewer.as:57]
at AWDViewer()[C:\Users\wintec\Desktop\Flash3DViewer\source\AWDViewer.as:49]
and that error line is just this
line 74 : stage.scaleMode = StageScaleMode.NO_SCALE;
line 57 : initEngine();
line 49 : init();
and I know that error message mean there's no properties that name.
I checked that, there's nothing wrong.
also, when I loading another swf file in my 'Main'swf, that's works. weird...
I don't understand why this error kept showing.
please help me.
below code is from Main.as
package
{
import flash.display.MovieClip;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.Event;
public class Flash3DViewer extends MovieClip
{
private var _request:URLRequest = new URLRequest("AWDViewer.swf");
private var _loader:Loader = new Loader()
public function Flash3DViewer()
{
init();
}
private function init():void
{
stop();
_loader.load(_request);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, initLoaded);
}
private function initLoaded():void
{
_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, initLoaded);
var extSwf = _loader.content as MovieClip;
swfContainer.addChild(extSwf);
trace("contents loaded");
}
}
}
I found the issue with your application based on the code you provided via DropBox. And just as I suspected, the stage property was being referenced before the object's addition to the stage was completed, which is why the null reference error was being generated.
The AWDViewer class was prematurely calling the stage property from one of the functions that is being called when the init function is called. I've updated the Flash3DViewer.as and AWDViewer.as files with the proper usage of the ADDED_TO_STAGE event so that this does not occur. I have also added comments to the code for you to follow along. Also, I had to modify the init function in the AWDViewer class to take a parameter of type Event to account for the fact that the function is now called when the ADDED_TO_STAGE event fires.
Flash3DViewer.as:
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.Event;
public class Flash3DViewer extends MovieClip
{
private var loader:Loader;
public function Flash3DViewer():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
loadSWF("AWDViewer.swf");
}
private function loadSWF(url:String):void
{
var urlRequest:URLRequest = new URLRequest(url);
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded, false, 0, true);
loader.load(urlRequest);
addChild(loader);
}
private function onLoaded(e:Event):void
{
var target:AWDViewer = e.currentTarget.loader.content as AWDViewer;
trace(target);
//target.init(); // no longer need to call the init function manually as the AWDViewer calls it when it 'knows' it has been added to the stage. This line can be deleted.
addChild(target);
}
}
}
AWDViewer.as:
public function AWDViewer()
{
/* Used ADDED_TO_STAGE event to know when to trigger the init
function call to avoid the null reference errors when accessing
the 'stage' property */
addEventListener(Event.ADDED_TO_STAGE,init);
// init(); // no longer need to manually call the init function as the ADDED_TO_STAGE event listener will take care of this. This line can be deleted.
}
/**
* Global initialise function
*/
public function init(e:Event):void
{
initEngine();
initListeners();
AssetLibrary.enableParser(AWD2Parser);
//kickoff asset loading
var loader:Loader3D = new Loader3D();
loader.load(new URLRequest("assets/monkey.awd"));
_view.scene.addChild(loader);
}
While I did attempt to compile the code above, and the null reference errors ceased to generate with my corrected code, there were some compiler errors on my machine because of the different configurations of our computers. You'll just need to ensure that these compiler errors do not appear on your machine.
Warning: Library path "C:\Users\wintec\Desktop\3D_VR\source\libs" does not resolve to a valid directory.
Warning: Library path "$(FlexSDK)/frameworks/libs/flex.swc" does not resolve to a valid file.
If you have any other questions, just let me know.
Cheers.
That error means that you are trying to access something which has not been instantiated. You should put some breakpoints and run your app in debug mode when you are not sure what exactly is null.
It's very likely that stage is null in your case. Stage property of DisplayObject is set to the instance of app's stage when this display object is added to stage. However, all parents of this display object should be added to the stage too. Thus, make sure that the instance of Flash3DViewer has the stage before loading AWDViewer.

Event ADDED_TO_STAGE executed two times as3 when I am using it on external swf

I got problem when I am loading external swf which contains added_to_stage method. It execute two times. I don t understand why it is doing ? I am also interesting if both swfs have their own stage ?
Thank you for any answer
I am using greensock library to hanle loading.
Flash preloader:
package {
import flash.display.MovieClip;
import com.greensock.loading.SWFLoader;
public class Preloader extends MovieClip
{
public function Preloader()
{
var loader : SWFLoader = new SWFLoader("Prototype1.swf");
loader.load();
addChild(loader.content);
}
}
}
External SWF:
public class Prototype1 extends MySprite
{
public function Prototype1()
{
addEventListener(Event.ADDED_TO_STAGE, onAdded);
}
private function onAdded(e:Event):void
{
trace("onAdded");
}
}
OUTPUT: onAdded onAdded
The greensock documentation says:
suppressInitReparentEvents: Boolean - If true, the SWFLoader will suppress the REMOVED_FROM_STAGE and ADDED_TO_STAGE events that are normally dispatched when the subloaded swf is reparented into the ContentDisplay (this always happens in Flash when any DisplayObject that's in the display list gets reparented - SWFLoader just circumvents it by default initially to avoid common problems that could arise if the child swf is coded a certain way).
So you can change your code in Preloader.as to:
var loader:SWFLoader = new SWFLoader("Prototype1.swf", {suppressInitReparentEvents: true});
And you'll only get one call to onAdded.

TRIED ALMOST EVERYTHING: ypeError: Error #1009: Cannot access a property or method of a null object reference

I am having this problem and cant get around it at all
im making a platform game for uni
i have 2 files
flashgame.fla and Coin.as (this is code for the Coin class)
i have code stating that once the player has collected all the coins the frame will change from frame 1 to frame 2.
When i do i receive this message
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at Coin/update() TypeError: Error #1009: Cannot
access a property or method of a null object reference. at
flashgame_fla::MainTimeline/loop()
i have tried Try and Catch and various other things
I think it does this because the Coin.as extends MovieClip so when it goes to the next frame it is still trying to find a coin when nothing is there.
here is the code for Coin.as
package {
import flash.display.MovieClip;
import flash.events.*;
public class Coin extends MovieClip {
var player:MovieClip;
var mainTimeLine = MovieClip(root);
public function Coin() {
this.addEventListener(Event.ENTER_FRAME, update);
}
function update(event:Event):void
{
player=MovieClip(root).player;
if(this.hitTestObject(player))
{
this.removeEventListener(Event.ENTER_FRAME, update);
parent.removeChild(this);
mainTimeLine.coinCount++;
}
}
}
}
i have an array in flashgame.fla that records all coins in the game. when the player hits them they are spliced from the array. could also be causing the problem when going to frame 2
important stuff from flashgame.fla
var coin:Array = new Array();
for (i=0; i<numChildren; i++)
{
if (getChildAt(i) is Coin)
{
coin.push(getChildAt(i).getRect(this));
}
}
splicing coins
for (i=0; i<coin.length; i++)
{
if (player.getRect(this).intersects(coin[i]))
{
coinSnd.play();
coin.splice(i,1);
}
}
Thanks for any help given
if you need anything more from me please ask :)
all g with screenshots
It's most likely because the player cannot be found in the update function in the Coin class. This is because ENTER_FRAME events are run even if the display object is not on the stage, which you often don't want. In this case you try to do a hittest against the player.
To solve this, you can start running update as soon as the Coin is attached to the stage and stop running it as soon as it's removed from the stage.
public function Coin() {
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
this.addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
}
function onAddedToStage(event:Event):void {
this.addEventListener(Event.ENTER_FRAME, update);
}
function onRemovedFromStage(event:Event):void {
this.removeEventListener(Event.ENTER_FRAME, update);
}
Which line number is the error occurring on? That should tell you which variable is null.
My guess, based on this part of the error: "TypeError: Error #1009: Cannot access a property or method of a null object reference. at Coin/update()", is that the parent of the coin is null because you've moved to a new keyframe and the instance has been removed from the stage.
That is, I suspect the error is occurring on the line with parent.removeChild(this); - is this correct?
If that's the case then check whether parent is not null before calling removeChild on it.