Declaring variable in different class not working as3 - actionscript-3

I have a public var called monster number in my monster class.
public var monsterNumber:int;
And in my document class, I want to give monsterNumber a number, lets say 5.
It's still tracing monsterNumber as 0 in my monster class, but 5 in my document class. Is there any way to change this var in my document class?

Here's an example of how you can create a instance of Monster and modify it's property monsterNumber :
// in your document class
var monster:Monster = new Monster();
monster.monsterNumber = 1;

You can define your variable as a static variable so you can change its value from anywhere you want.

Related

How to reference a variable from a class to a scene in ActionScript 3.0

I am creating a platformer in flash as3 and i want to pass the var Score for my score from Scene 1 to the next. However, I realized the best way to do this was to store the score inside a class, but I am having trouble referencing the variable inside the scenes. Please help. This is the code currently inside the class
package file_as{
public class CS{
public function CS(){
public var Score:Number = 0;
}
}
}
I tried to reference the score in scene in the frame containing my code my stating
CS.Score
But that didn't work so I'm lost.
To access it by doing CS.Score you would need to make that property static.
Static vars/methods belong to the class itself (CS in this case), if not static, they belong to instances of that class (eg var csInstance:CS = new CS(); csInstance.Score = 6;)
Here is how to make it static:
package file_as{
public class CS{
public static var Score:Number = 0;
}
}
As an aside, your current class code should be throwing an error, as you can't have the public/private keywords inside a function. Also, since you defined the var inside a function (the constructor in your case) it would only be available in that function. Notice how in my example above the var definition is at the class level.
All this said, I believe that if you defined a score var on your main timeline, it should be available across different scenes.

AS3: How do I access a variable from a parent object?

I'm new to AS3 and my code may look a bit off.
Basically, how my program works is that I have an instance of "Level" on the stage, and it is a MovieClip containing several other objects which are also MovieClips with their own document class. In the "Level" class, I can access the X and Y position from the instance of "Player", but in my "Arrow" class, which is also a child of Level, I'm unable to access the X and Y of "Player". What I tried to do is set a public static variable called playerX and playerY in the Level class and assign that to the player's x and y position every frame, and I try accessing the variable in the Arrow class by doing "var x:Number = Object(parent).playerX, I've also tried MovieClip(parent).playerX and parent.playerX and just player X, neither of them work.
So to sum it up, I need to access a variable from a parent class, but every way I have tried it just returns an error.
Sorry if this was a bit unclear, any help will be much appreciated!
Sounds like you are using FlashPro Timelines, and have two siblings objects (they have the same parent MovieClip/timeline) and you want to be able to reference one from the other (let me know if this doesn't properly summarize your question).
Since it sounds like you have class files attached to your Arrow and Player classes, you'll want to make sure any code referencing the parent or stage or root vars is run AFTER the item has been added to the display list as those vars are only populated after the item has been put on the stage. (this isn't an issue for timeline code).
So, something like this:
public class Arrow extends MovieClip {
public var player:Player; //a var to hold a local reference to the player
public function Arrow():void {
//right now parent/stage/root are null
//listen for the added to stage event, so you know when it's safe to use the parent and stage and root keywords
this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function addedToStageHandler(e:Event):void {
player = MovieClip(parent).playerInstanceName;
//where player instance name is the instance name of your player on the parent timeline
}
private function doSomethingWithPlayer():void {
if(player){
player.x = 5;
}
}
}
Now, if you wanted to use a Static var instead (might be less cumbersome than the parent keyword), and there is only ever 1 player instance, you could do the following:
public class Player extends MovieClip {
//create a static var to hold a reference to the player instance
public static var me:Player;
public function Player():void {
me = this; //now assign the instance to the static var.
}
}
Now, you can access the player instance from anywhere in your app by doing Player.me (regardless of context)
Player.me.x = 5;
You need to understand what a static variable is and what it is not. A static variable IS a Class variable, A static variable IS NOT an instance variable. So if I create a static variable called "playerX" in a class called "Level" I can now do this:
Level.playerX = 0;
Because Level is a class and playerX is a variable of that class.
I cannot do this:
Object(parent).playerX
Because 'parent' is not a class and does not have a variable called 'playerX', parent might be an instance of the class 'Level' but instances of the class 'Level' do not have a variable called 'playerX', the class itself "Level" is the one that has that variable.

Objects within Objects

I have an object in my Library called Bottle. Bottle is made up of "Glass" and "Cap" instances. There are two more symbols in my library called Cap, and Glass.
When I click on the cap of Bottle, it says that this object is of class Cap, and when I click on the glass, it says it is of type Glass. Each one of these objects has base class flash.display.MovieClip.
However, in my code when I do:
var bottleOnStage:Bottle = new Bottle();
addChild(bottleOnStage);
var newColor:uint = 0x00ff00;
var newColorTransform:ColorTransform = new ColorTransform();
newColorTransform.color = newColor;
bottleOnStage.Glass.transform.colorTransform = newColorTransform;
I get this error:
TypeError: Error #1010: A term is undefined and has no properties. at MethodInfo-1()
Am I accessing the Glass property wrong? Is it because I haven't created an instance of Glass? I am confused on how objects within objects work in Flash.
EDIT
var cap:Cap;
var glass:Glass;
Above is what is in my Bottle.as file. In my Main.as file I have:
var bottleOnStage:Bottle = new Bottle();
bottleOnStage.cap = new Cap();
bottleOnStage.glass = new Glass();
addChild(bottleOnStage);
var newColor:uint = 0x00ff00;
var newColorTransform:ColorTransform = new ColorTransform();
newColorTransform.color = newColor;
bottleOnStage.glass.transform.colorTransform = newColorTransform;
When I run this code, no changes occur to the "glass" portion of the bottle. Why is this? I know that it is this line; I have traced and debugged all of the other lines, and the colors I am tracing are correct, etc. When I add "cap" and "bottle" to "bottleOnStage" using addChild, I get a duplicate of these two symbols, so this is apparently not the way. Basically, how do I modify "cap" and "glass" on stage?
It looks like your are confusing Classes with instances. Instance names cannot have the same name as a Class name (in the same scope).
Glass is your class. If you have variable with the name of "Glass" inside your bottle class, you need to rename it so it isn't ambiguous with your class name Glass.
bottleOnStage.glassInstanceName.transform.colorTransform = newColorTransform;
As a tip, to avoid this situation best practice is always make your instance names begin with a lower case letter, and always make your Class names begin with an upper case letter. (That also helps with code highlighting in most coding applications as well as here in Stack Overflow - notice how your uppercase items are hightlighted?)
As far as your error goes, you likely don't have an actual object in your variable yet.
Doing the following:
var myGlass:Glass;
Doesn't actually make an object (the value is null), it's just defining a placeholder for one. You need to instantiate using the new keyword in order to create an actual object.
var myGlass:Glass = new Glass();
Now you'll have an object in that variable.
EDIT
To address your edit, sounds like your probably want to something like this:
package {
public class Bottle extends Sprite {
public var cap:Cap;
public var glass:Glass;
//this is a constructor function (same name as the class), it gets run when you instantiate with the new keyword. so calling `new Bottle()` will run this method:
public function Bottle():void {
cap = new Cap();
glass = new Glass();
addChild(cap); //you want these to be children of this bottle, not Main
addChild(glass);
}
}
}
This keeps everything encapsulated and adds the cap and glass as children of the bottle. So bottle is a child of main, and cap and glass are children or bottle.
Whats is the name of the Glass attribute in the bottle?
if you have for example:
public class Bottle {
public var glass : Glass;
}
You can access the glass with:
var bottle : Bottle = new Bottle();
bottle.glass = new Glass();
Glass is the class. bottle.glass is the attribute "glass" of the class Bottle.
Hope it helps.

Flash AS3: How to create one function to play sounds from different buttons?

I am making a soundboard and I'm using actionscript. I would like to have one function with the code to play a different sound depending on which button is pressed. I will also be playing from the library rather than a URL. Here is some real code mixed with pseudo for what I want to do:
var soundEffect:SoundEffect = new SoundEffect();
sound1_btn.addEventListener(MouseEvent:CLICK, buttonName, playSoundEffect); //possible?
function playSoundEffect(e:Event, buttonName):void {
soundEffect.attachSound = buttonName + ".mp3" //pseudo code
soundEffect.play();
}
The SoundEffect class is just the name I used in Linkage. I don't know the best way to change the sound that a class represents, or the best way to do this in general. Ideally I'd like to not create 50 different classes with 50 different sound variables and 50 functions. I'd rather each button had some sort of identifier and within the function I can use the button name or identifier to assign the appropriate sound.
If you are using a Button symbol, you could use a naming convention that encodes the class name in your button name.
So if your sound effect class name was sfx_jump , you would name your instance :
sfx_jump_btn
You then set your event listener like this :
sfx_jump_btn.addEventListener(MouseEvent.CLICK, clickHandler);
What you want to do in the clickHandler function is to first generate your className String based on the buttons name property. Then you get the Class Definition via using getDefinitionByName so that you can create an instance of the sound, the following code is how you do that :
public function clickHandler(e:MouseEvent):void
{
var button:SimpleButton = e.target as SimpleButton;
// use replace to clip off the _btn suffix
var className:String = button.name.replace("_btn","");
var SoundClass:Class = getDefinitionByName(className) as Class;
var newSound:Sound = new SoundClass();
newSound.play();
}
You also need to add this import :
import flash.utils.getDefinitionByName;
Yes you can do it. Since you have multiple buttons attach a property to each button like below I attached 'soundToPlay' property to sound1_btn.
sound1_btn.soundToPlay = "1.mp3";
sound1_btn.addEventListener( MouseEvent.CLICK, handleBtnClick);
function handleBtnClick( e:Event ):void{
soundEffect.attachSound = e.target.soundToPlay;
soundEffect.play();
}
#hrehman have the answer for you, but if you button class don't have the property soundToPlay you could use the name property as an ID. and get back with the currentTargetproperty of the event.
sound1_btn.name = "Sound1";
sound1_btn.addEventListener(MouseEvent:CLICK, playSoundEffect);
function playSoundEffect(e:Event):void {
soundEffect.attachSound = e.currentTarget.name + ".mp3";
soundEffect.play();
}

how to create a AS3 dynamic class and how to use it?

What is a dynamic class and what are its uses and how to create and use a dynamic class?
Can anyone guide me to a good tutorial please?
Here You can find basic info : http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/statements.html#dynamic
Dynamic class allow You to add additional dynamic params to object in run-time .
For example : Sprite isnt dynamic , so You cannot do thing like :
var sprite:Sprite = new Sprite ();
sprite["value"] = 10; // this will throw ReferenceError
But MovieClip is dynamic instance that allow You to add dynamic params :
var mclip:MovieClip = new MovieClip();
mclip["value"] = 10;
To make class instance dynamic , You have to add 'dynamic' key word to declaration :
public dynamic class MyClass { ...
A dynamic class is basically one that can be modified at runtime. One of the main uses of this feature is when extending the Proxy class.
A couple of good examples:
http://manishjethani.com/archives/2008/08/25/jsonobject-for-reading-and-writing-json-in-actionscript
http://manishjethani.com/archives/2008/12/19/guaranteeing-enumeration-order-in-for-in-loops