AS3 - types and classes - actionscript-3

I'm not exactly sure but i'm guessing my problem has to do with how i'm declaring my variables.
Is the below code legal in AS3?
var fish1:Fish = new Fish;
var fish2:Fish = new Fish;
var fish3:Fish = new Fish;
var fish4:Fish = new Fish;
addChild(fish1);
addChild(fish2);
addChild(fish3);
addChild(fish4);
fish1.x = 0;
fish2.x = 150;
fish3.x = 300;
fish4.x = 450;
i'm getting compiler errors for each line of addChild saying:
Main.as, Line 14 1180: Call to a possibly undefined method addChild.
Main.as, Line 14 1120: Access of undefined property fish3.
and for every line where i'm specifying the x coordinates of my fish i'm getting
a compiler error saying
Main.as, Line 15 1120: Access of undefined property fish4.
the fish variables are of type Fish and I've defined them in my library in my .fla file.
Thank you in advanced!

Your Class needs to subclass some form of DisplayObjectContainer, of which MovieClip and Sprite are two possible choices (find out, be sure).
But I suspect that the real probem is you're writing Class code like it's timeline code. I think you probably have strict mode off, which is why you're ot getting helpful compile-time errors which would help anyone who's familiar with AS3 (though probably not you) to figure out immediately that your code should look more like
class Main extends Sprite {
public var fish1:Fish = new Fish();
public var fish2:Fish = new Fish();
public var fish1:Fish = new Fish();
public function Main() {
addChild(fish1);
addChild(fish2);
addChild(fish3);
//not going to type this crap.
//positioning code (and addChild) is a waste of time.
//that's what the stage is for!
}
}

Related

How can I call timeline-specific methods from an external file in AS3?

I'm creating a game is Flash CS5 with ActionScript 3. To simplify things, I've created a file (Game.as) in the top layer of my source folder. My Game.as file looks as follows:
package {
public class Game {
public static function fail():void {
stop();
var restart:RestartButton = new RestartButton();
addChild(restart);
restart.x = stage.stageWidth/2;
restart.y = stage.stageHeight/2;
Game.createButton(restart, function(e:MouseEvent):void { gotoAndPlay (1, "Title Sequence") });
}
}
}
I would supposedly call Game.fail () from a frame on a timeline a scene, but I get these compiler errors:
Line 11 1180: Call to a possibly undefined method stop.
Line 19 1180: Call to a possibly undefined method gotoAndPlay.
Line 17 1120: Access of undefined property stage.
Line 16 1120: Access of undefined property stage.
Line 14 1180: Call to a possibly undefined method addChild.
Why are these errors happening? What can I do to fix them?
Thanks for your help in advance.
The problem is that none of those methods exist on your Game class.
There's at least two good reasons for this:
Your Game class needs to extend MovieClip to have the methods stop(), gotoAndPlay(), addChild(), and the stage property. For example class Game extends MovieClip would give you those methods.
Even if your Game extends MovieClip you can't access methods like stop() from static scope, only from instance scope (ie this). This is because static scope is essentially a global code space so none of those methods make any sense: when you say stop() you have to say what instance will stop, ex this.stop() or thatThing.stop(). The static code has no awareness of what instances of the class there may even be, so there's no way an instance function can work. You need an instance of the Game class, not just a static function.
What I think you are trying to do is essentially use Game as a singleton for your main timeline. You can do that like this:
package {
public class Game extends MovieClip {
// global reference to a single instance of the Game
public static game:Game;
public function Game() {
// store a global reference to this instance
// NOTE: bad things will happen if you create more than one Game instance
game = this;
}
// do NOT use static for your methods
public function fail():void {
stop();
var restart:RestartButton = new RestartButton();
addChild(restart);
restart.x = stage.stageWidth/2;
restart.y = stage.stageHeight/2;
createButton(restart, function(e:MouseEvent):void { gotoAndPlay (1, "Title Sequence") });
}
}
}
Now you need to set this class as your document class. There is only ever one instance of the document class, so this works well for you. However, you could link this class to a symbol in your library and instantiate it by code (new Game()) or by placing a timeline instance on a keyframe.
Finally, to call Game methods from anywhere you can use the Game.game instance:
Game.game.fail();

TypeError: Error #1009: Cannot access a property or method of a null object reference. The object isn't null

Okay, so my game codes are not problematic at all and don't effect the game UNLESS I declare the level "OneManager" as a variable.
OneManager is the class for my level. The level is a movieclip containing all the level's components. And Main is the document class.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at OneManager()[C:\Users\Jay\Creative Cloud Files\Subject 51 Experimental\OneManager.as:38]
at Main()[C:\Users\Jay\Creative Cloud Files\Subject 51 Experimental\Main.as:16]
I don't think it makes any sense. I deleted line 38, then the problem indicated until line 39, then I deleted them over and over. Then practically until my code was useless, that's when I FINALLY got no error...
These codes don't even look problematic at all. I even tried adding them manually by adding the class's movieclip to the stage myself and it worked completely fine. But what I'm trying to do is add it to the stage through code by making this class's movieclip a variable and when the button is clicked, but if I did that - I would get these random errors from other classes.
I'm not sure what's wrong here. There is no trouble compiling, so I get no compile errors. Only errors from the output. These lines of codes aren't null, but the output says it is. I'm confused.
Please help, thanks!
Code for Main Document Class:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class Main extends MovieClip
{
var mountains: Mountains;
var homePage: HomePage;
var oneManager: OneManager;
public function Main()
{
mountains = new Mountains;
homePage = new HomePage;
oneManager = new OneManager;
addChild(homePage);
homePage.playButtons.addEventListener(MouseEvent.CLICK, onPlayButtonsClick);
}
function onPlayButtonsClick(event:MouseEvent):void
{
//var level1Page = new Level1Page;
removeChild(homePage);
addChild(oneManager);
}
}
}

Actionscript 3 addChild problems

The error messages from FlashDevelop are rather difficult to translate.
I'm using addChild in several situations, generally with no problems. However, every once in a while I get:
Error: Call to a possibly undefined method addChild.
However, the exact same code works in other classes, and I am importing exactly the same files. Obviously addChild is not an undefined method! Here's the code- works in one module, doesn't work in another.
public var artist:Loader;
public var artistName:Loader;
public function SceneTJ():void {
artistName = new Loader();
artistName.load(new URLRequest("images/artistname.jpg"));
artist = new Loader();
artist.load(new URLRequest("images/artist.jpg"));
artistName.x = artistName.y = 0;
artist.x = 0;
artist.y = 0;
addChild(artist);
addChild(artistName);
}
Got it. Like a dummy, I forgot to add "extends Sprite" after the class declaration.

ActionScript code problems

I have only recently started to learn ActionScript 3.0 I was practising in Flash and i ran into this problem:
Scene 1, Layer 'Layer 1', Frame 1, Line13 1119: Access of possibly undefined property dosomething through a reference with static type flash.net:SharedObject.
What i am tring to do is use the SharedObject.send method to send a message obviously. I have edited some server side code in my main.asc file. And i am trying to pass in the doSomething function but i get that compile error.
Any advice would be appreciated for a novice like myself.
The code is below:
import flash.net.NetConnection;
import flash.net.SharedObject;
var nc:NetConnection = new NetConnection();
nc.connect("rtmp:/exampletest/");
var so:SharedObject = SharedObject.getRemote("foo", nc.uri, true);
so.connect(nc);
so.dosomething = new function(str) {
If you want to pass a function between SWFs, attach the function to the .data member of the SharedObject returned by SharedObject.getLocal/Remote, not the SharedObject itself.
So:
so.data.doSomething = yourFunction
...should work. I'm not exactly sure what you're trying to achieve, does this sound like a solution?

ActionScript 3.0 Error #1010 - preloader function

I am a Flash and ActionScript newbie. I am trying to follow a video tutorial to make a preloader and I'm having a problem that the video didn't seem to address. I believe I have entered in all of the code correctly from the video. This is it:
stop();
addEventListener(Event.ENTER_FRAME, loaderF);
function loaderF(e:Event):void{
var toLoad:Number = loaderInfo.bytesTotal;
var loaded:Number = loaderInfo.bytesLoaded;
var total:Number = loaded/toLoad;
if( loaded == toLoad ){
removeEventListener(Event.ENTER_FRAME, loaderF);
gotoAndStop(2);
} else {
preloader_mc.preloaderFill_mc.scaleX = total;
preloader_mc.percent_txt.text = Math.floor( total * 100 ) + "%";
preloader_mc.ofBytes_txt.text = loaded + "bytes";
preloader_mc.totalBytes_txt.text = toLoad + "bytes";
}
}
What I typed in doesn't generate a compiler error, but the output tells me:
TypeError: Error #1010: A term is undefined and has no properties.
at preloader_fla::MainTimeline/loaderF()
And since I really don't have any experience outside of what I'm learning from this tutorial series, I don't know what to do to fix this.
I don't use Flash CS5, but you should be able to get the line # for where the error is occurring, I believe, by executing the SWF by pressing CTRL+SHIFT+ENTER.
Once you get the line number, you should see that something on that line is null or not defined. The error says it occurs in the function loaderF(), and looking at that code the only place such an error could occur is in the else block:
} else {
preloader_mc.preloaderFill_mc.scaleX = total;
preloader_mc.percent_txt.text = Math.floor( total * 100 ) + "%";
preloader_mc.ofBytes_txt.text = loaded + "bytes";
preloader_mc.totalBytes_txt.text = toLoad + "bytes";
}
In the above code block, one of these things is not defined:
preloader_mc.preloaderFill_mc,
preloader_mc.percent_txt,
preloader_mc.ofBytes_txt,
preloader_mc.totalBytes_txt
Maybe your preloader movie clip is missing one of these objects...
First, you'll want to turn on debugging found under (File > Publish Settings > Flash (.swf) > Permit Debugging). This will provide line numbers and allow additional debugging to help track down errors.
Secondly, in the code sample you've provided, you haven't declared a loader, so when you call on loaderInfo, it makes sense that flash complains about "a term is undefined". Although, technically, the loaderInfo object is a child of the event object. Thus, loaderInfo.bytesTotal would become e.loaderInfo.bytesTotal, assuming you added the event listener to the loader object; currently yours is added to the timeline.
Bookmark Adobe's Actionscript 3.0 Reference. Use it. As you begin your journey in Flash, this will be your indispensable handbook to speaking AS3. Specifically, you'll want to refer to the Loader class.
Here's what you're likely missing in your code:
var myLoader:Loader = new Loader();
myLoader.load(new URLRequest("path/to/my/file"));
Your function loaderF is being called during every frame update to the screen (likely every .034 seconds). You'd probably be happier with ProgressEvent.PROGRESS instead of Event.ENTER_FRAME. If so, you'll also want to catch the complete event, and that'd look like this:
myLoader.addEventListener(Event.COMPLETE, loadComplete);
myLoader.addEventListener(ProgressEvent.PROGRESS, loadProgress);
function loadComplete(e:Event):void {
// Stuff to do when the file finishes loading.
}
function loadProgress(e:Event):void {
var current:int = e.bytesLoaded;
var total:int = e.bytesTotal;
var percent:Number = current/total;
// Update the readout of your loading progress.
}
Hopefully that points you in the right direction. :)