Global variables in action script 3 - actionscript-3

I'm new in action script 3. I intend to use global variable.
Here some way to do this and this
I download simple banner from here
Create file Globe.as in the same directory as test_banner_actionscript_3.fla. Globe.cs contains next code
package
{
public class Main
{
public static var myPencil:Number = 3;
}
}
banner code looks like this
mybanlink.addEventListener(MouseEvent.CLICK, mybanlinkClickListener);
function mybanlinkClickListener(e:MouseEvent):void {
trace(Main.myPencil); //3
var url:String="http://www.web-article.com.ua";
var urlRequest:URLRequest=new URLRequest(url);
navigateToURL(urlRequest);
}
but I get
error: 1120: Access of undefined property Main
Interesting that Intellisense suggests "myPencil" when typing "Main."
What's wrong?

You possibly forgot import Main in the begin of your banner code. Remember, when you use a class, always check that this class is imported.

Related

Flash/AS3 Use variable in multiple scenes

I need a simple way to access a variable from different scenes. I already read a lot of answers but nothing worked.
There has to be a easy way to do this!
You can try this library:
https://github.com/inruntime/AS3-Global-Object
Usage:
import com.inruntime.utils.*
//This is need every time you'll use the Global Instance
public var $:Global = Global.getInstance();
$.x = 1;
//access it
trace($.x);
you can even pass functions
function myFunction(name:String){
trace(name);
}
$.myfunc = myFunction;
//use the function
$.myFunc("NoName");
//output
NoName
All scenes are part of the same timeline, so any variable you place on the main timeline is by default accessible across all scenes:
// Scene 1 main timeline
var message:String = "Hello World";
// Scene 2 main timeline
trace(message); // "Hello World"
Likewise, the document class is shared across all scenes, so any vars defined on the document class can be accessed across all scenes.
Lastly, if you are looking for an easy way to access variables from anywhere, not just across scenes, you can use class static scope:
// Main.as
package {
public class Main {
public static var message:String;
}
}
// from anywhere
Main.message = "Hello World";
// from anywhere else
trace(Main.message); // "Hello World"

Can I still create Global variables in AS3

Following the answer here, I have created a file called MyGlobals.as and placed some global variables and functions so that I can access it from anywhere within my project just like AS3 buil-in functions such as trace() method.
This is MyGlobals.as which is located in the src folder (top level folder)
package {
public var MessageQueue:Array = new Array();
public var main:Main;
public var BOOKING_STATUS_DATA:Object;
public function postMessage(msg:Object):void {
MessageQueue.push(msg);
}
public function processMessage():void {
var msg:Object = MessageQueue.pop();
if (msg) {
switch (msg.type) {
}
}
}
Looks like my IDE (FD4) is also recognizing all these functions and variables and also highlighting the varibles and functions just like any other built-in global functions. However, I am getting compilation errors "Accessing possibly undefined variable xxx". The code is as simple as trace(MessageQueue) inside my Main (or another classe).
I am wondering if there was any change Adboe has done recently that it can't be done now or am I missing something? I am not sure if I need to give any special instructions to FD to include this MyGlobals.as?
I am using FD4, Flex SKD 3.1, FP12.0
I am aware of the best practices which suggests to avoid using this type of method for creating global variables but I really need it for my project for my comfort which I feel best way (right now) when compared to take any other path which involves daunting task of code refactoring. I just want do something which can be done in AS3 which I guess is not a hack.
I've done some playing around; it looks like you can only define one (1) property or method at package level per .as file. It must be the same name (case-sensitive) as the .as file it is contained in.
So no, nothing has changed since the older Flash Versions.
In your case that would mean you need five separate ActionScript files along the lines of:
MessageQueue.as:
package
{
public var MessageQueue:Array;
}
main.as:
package
{
public var main:Main;
}
...etc. As you can see this is very cumbersome, another downside to the many others when using this approach. I suggest using the singleton pattern in this scenario instead.
package{
public class Singleton{
private static var _instance:Singleton=null;
private var _score:Number=0;
public function Singleton(e:SingletonEnforcer){
trace(‘new instance of singleton created’);
}
public static function getInstance():Singleton{
if(_instance==null){
_instance=new Singleton(new SingletonEnforcer());
}
return _instance;
}
public function get score():Number{
return _score;
}
public function set score(newScore:Number):void{
_score=newScore;
}
}
}
then iin your any as3 class if you import the singleton class
import Singleton
thn where u need to update the global var_score
use for example
var s:Singleton=Singleton.getInstance();
s.score=50;
trace(s.score);
same thing to display the 50 from another class
var wawa:Singleton=Singleton.getInstance();
trace(wawa.score)

ReferenceError: Error #1065: Variable TestMain is not defined

I'm loading a .swf and trying to find a class based on an embedded xml document in it. I've looked this problem up endlessly and everyone has either said "Your class isn't public", "Your classname is interfering with your document class", or "You aren't using the same ApplicationDomain", none of which are true. Here's my code:
In CoCMain.as, with a CoCMod.fla:
private function pluginLoadingComplete(e:Event):void {
var testXML:XML = new XML(new e.target.content.description);
trace(e.target.applicationDomain.hasDefinition("blah.blaah.testPlugin.TestMain"));//returns false
trace(ApplicationDomain.currentDomain.hasDefinition("blah.blaah.testPlugin.TestMain"));//returns false
trace(testXML.main[0]);//returns blah.blaah.testPlugin.TestMain
var pluginClass:Class = e.target.applicationDomain.getDefinition(testXML.main[0]) as Class;//error here
}
And in TestMain.as, with a TestMod.fla (this is the swf I am loading):
package blah.blaah.testPlugin {
public class TestMain {
public function TestMain():void {
super();
}
public function onEnable():void {
trace("blah");
}
}
}
And in frame 1 of TestMod.fla:
import blah.blaah.testPlugin.TestMain;
[Embed(source = 'main.xml', mimeType = "application/octet-stream")]
const description:Class;
The xml file:
<mod>
<name>Test Mod</name>
<description>Please ignore</description>
<author>Bleachisback</author>
<version>1.0</version>
<main>blah.blaah.testPlugin.TestMain</main>
</mod>
The error I am getting:
ReferenceError: Error #1065: Variable TestMain is not defined.
at flash.system::ApplicationDomain/getDefinition()
at me.bleachisback.cocMod::CoCMain/pluginLoadingComplete()
This sounds like a similar problem to what I encountered - where you're trying to dynamically create an instance from the descriptive name.
If you don't explicitly instantiate an instance of your target class, the compiler won't include your target class in the build, so the class doesn't exist (hence your error). So, you could add the line
var xyz:TestMain = new TestMain();
but that sort of defeats the purpose...
You can force the compiler to include your class by using the includes directive, with the list of classes that must be included.
Did you try this?
var pluginClass:Class = e.target.applicationDomain.getDefinition(testXML.main.text().toString()) as Class;

Where can I define a class globally?

I have a class, and I'd like to make it available for use anywhere within a Flash project. Where should I put it? Ideally, it'd be in a separate ActionScript file.
If your ActionScript 3 project using classes, you can simply create global variable using public static like this :
//MyClass.as
package {
public class MyClass {
public static var myValue = 3;
}
}
//Arbitrary.as
package {
public class Arbitrary {
function Arbitrary():void {
trace(MyClass.myValue); //3
}
}
}
You in every project, follow these steps to enable.
Click ActionScript 3.0 Settings...
Click Source path folder icon, select a you want src folders.
You can use top level default package declaration.
package com.abc.globals
{
//Note here No Class Declaration
public var globalVars:String = "Global is horrible";
}
So that you can use without import statement and you can use access variable without class or instance.
It is like our trace("Hello Global").
globalVars will access from anywhere in application.

movie clip class parameters ane null

I have a movie clip with an external class attached.
here is the MC code (I've shorten it only for the relevant part...)
package {
//all the imports here...
public class mc_masterChapter extends MovieClip {
public function mc_masterChapter() {
trace (picFile,strChapTitle);
}
//Properties
public var picFile:String;
public var strChapTitle:String;
}
}
In the main class file I'm adding this object to stage using addChild:
var masterChapter:mc_masterChapter = new mc_masterChapter;
masterChapter.picFile = "pic_Chap1.jpg";
masterChapter.strChapTitle = "ABCD:
addChildAt(masterChapter,1);
now, the trace in the MC class code gives nulls to both parametes but if i put a trace inside the MC timeline (instead of the attached class code), it gives the right value!
how can I access the values from the MC class itself without getting nuls?
Thank you.
It works! Let me explain:
var masterChapter:mc_masterChapter = new mc_masterChapter; // Calls class constuctor
// so calls trace() too!
// You will get null null
masterChapter.picFile = "pic_Chap1.jpg"; // Assign the variables
masterChapter.strChapTitle = "ABCD"; // so they can be read
trace(masterChapter.picFile, masterChapter.strChapTitle); // Should trace pic_Chap1.jpg ABCD
If you add the following method to your class:
public function test():void {
trace(picFile, strChapTitle);
}
Then call masterChapter.test() it will successfully trace those two properties. So yes, the class can read its properties.
Make the var you use in your main class public static vars.
OK!
I solved the mystery.
I put two traces. one in the main MC class saying "hey, I'm inside the MC - the picFile="
and one in the put Function saying "I'm putting this file into picFile:"
well this is what I've got:
hey, I'm inside the MC - the picFile=null
I'm putting this file into picFile:image.jpg
got it!?! at the moment I asked him to give birth to an instance of the MC (even before putting it on stage - just defining the object (with this line:)
var masterChapter:mc_masterChapter = new mc_masterChapter;
it allready run the class, so of course that in this stage the parameters were not defined allready and were null.
the definition code came right after that line (in the main.as)
masterChapter.pic="pic_Chap1.jpg";
so what I did, was to move all the code from the main class of the MC object to a public function inside the same package called init(). Then I called this function manually from the parent main class.
By that I can decide when to call it (after I declare all the parameters of course).
That's it.
god is hiding in the small details : )
tnx for all the helpers.
Possibly a better solution would be to use a getter/setter pair, so you can know at the exact moment the properties are set:
protected var _picFile:String:
public function get picFile():String {
return _picFile;
}
public function set picFile(value:String):void {
if (value != _picFile) {
_picFile=value;
trace('picFile set to', _picFile);
}
}