AS3 Listen for the Enter Key to be pressed

Here’s a little Flash AS3 snippet that listens for the pressing of ENTER key using the Keyboard even listener.

this.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyEnterHandler);
function keyEnterHandler(event : KeyboardEvent) : void
{
if (event.keyCode == Keyboard.ENTER)
{
returnSavings_mc.visible=true;
}
}

How To Embed YouTube Videos In HTML5 And Flash Mode – SoftSailor

Found this tutorial on youtube how to’s, embedding Flash and HTML5

How To Embed YouTube Videos In HTML5 And Flash Mode – SoftSailor.

The YouTube video website contains millions of videos and most of them are being embedded to other websites with the Flash videotechnology. This is a great feature of Youtube videos and considering that all theweb browsers contain theAdobe Flash Player plug-in installed and so you are able of watching the embedded Youtube videos without any problems. But, when you’re using your mobile’s web browser the things change, because of the fact that mobile web browsers aren’t capable of understanding the Flash technology. Still, some newer mobile phones received support for HTML5, which is a technology which offers support for playing embedded Youtube videos by using the element, which makes all videos supported on the

mobile phones.

How To Embed Youtube Videos In An IFRAME

If you want your website to be used by both types of web browsers, mobile and desktop-based editions, then you need to embed videos on both Flash and HTML5 formats, and by doing this the PC users can view the Flash video and the mobile users can view th HTML5 video. So, the videos based on the IFRAME embedding code will automatically display FLASH or HTML5 video player, depending on what kind of web browser you’re using. This is done because the IFRAME automatically knows what type of browser or OS that you use and so it will use the HTML5 embedding code for mobile web browsers and the FLASH embedding code will be used for computers.

How to Embed YouTube Videos in both HTML5 and Flash Versions

Despite the fact the all the YouTube videos contain support for IFRAME video embedding code, the embed code needs to be written by you manually. In the near future the IFRAME format will be the default video embedding format used for YouTube, because it supports Flash and HRML5 video embedding formats.

Flash Book: ActionScript 3.0 for Adobe Flash CS4 Professional Classroom in a Book

You need to get this Flash book: ActionScript 3.0 for Adobe Flash CS4 Professional Classroom in a Book. CLICK HERE TO GET IT.

Here’s what it’s all about: The fastest, easiest, most comprehensive way to learn ActionScript® 3.0 for Adobe Flash CS4 Professional

ActionScript® 3.0 for Adobe Flash CS4 Professional Classroom in a Book contains 14 lessons. The book covers the basics of learning ActionScript and provides countless tips and techniques to help you become more productive. You can follow the book from start to finish or choose only those lessons that interest you.

Learn to add interactivity to Flash files using ActionScript 3.0: Control timelines and animation, write event-handling functions, and control loading of and interaction with data, text, video, sound, and images.

“The Classroom in a Book series is by far the best training material on the market. Everything you need to master the software is included: clear explanations of each lesson, step-by-step instructions, and the project files for the students.” —Barbara Binder, Adobe Certified Instructor, Rocky Mountain Training

Classroom in a Book®, the best-selling series of hands-on software training workbooks, helps you learn the features of Adobe software quickly and easily. Classroom in a Book offers what no other book or training program does—an official training series from Adobe Systems Incorporated, developed with the support of Adobe product experts.

Flash CS5 on the iPhone, Apps

At the MAX conference yesterday, Adobe announced that designers and developers will be able to use Adobe Flash Professional CS5 to create rich, interactive applications for the iPhone and iPod Touch.

This is NOT Flash Player running on the iPhone. There is no new information about Flash Player on the iPhone. This announcement means that Flash designers and developers can use Flash Professional CS5 and ActionScript 3 to build native applications that can be distributed and downloaded via the Apple App Store.

This new feature was demonstrated in a sneak peak of Flash Professional CS5. The new features of Flash Professional CS5 also include a new text engine for creative freedom and control with text, XML based FLAs to boost team collaboration on projects, prebuilt code snippets for rapidly adding interactivity, as well as integrations with Adobe Flash Builder to improve ActionScript editing. A beta of Flash Professional CS5 will be available later this year via Adobe Labs.

Adobe announces ability to publish ActionScript 3 projects to run as native iPhone apps. More info at http://www.adobe.com/go/iphone

Adobe Flash Pro CS5 beta coming, supporting native iPhone apps. Sign up and more info at http://www.adobe.com/go/flashprobeta

You can learn more about this announcement in the FAQ below as well as in the following places • Adobe News Room (http://www.adobe.com/aboutadobe/pressroom/) •

Information about apps for iPhone on Adobe Labs (http://www.adobe.com/go/iphone) • Information about Flash Professional CS5 on Adobe Labs (http://www.adobe.com/go/flashprobeta)

More about Flash Professional CS5

What did Adobe announce at MAX regarding Flash Professional?
Adobe previewed an early version of the next major version of Flash, Adobe Flash Professional CS5. Adobe also announced that a public beta of Flash Professional CS5 will be available for download from Adobe Labs later this year. That beta will include support for the ability to compile ActionScript 3® projects in Adobe Flash Professional to run as applications for iPhone. Interested designers and developers can go to Adobe Labs to sign up and to be notified when the beta is available.

What are the new features of Flash Professional CS5?
There are many new and exciting features in Flash Professional CS5. These include
• New text capabilities via the Text Layout Framework (TLF). Get unprecedented control and creativity with text in Flash projects. Advanced styling and layout, including right to left text, columns, threaded text blocks let you work with text in Flash like never before.
• XML based FLA files let you manage and modify project assets using source control systems, and enable teams to easily collaborate on files.
• Code Snippets panel provides pre-built code that can be injected into projects for greater interactivity and also reduces the ActionScript 3 learning curve. The panel includes code for timeline navigation (ie: click to go to the next scene) actions (ie: drag and drop), animation (ie: move with keyboard arrows), audio and video, event handlers (ie: mouse events) and loading and unloading of assets.
• Flash Builder integration. Use Flash Builder to write ActionScript code within Flash projects.
• Improved ActionScript editor, including custom class code-hinting and completion

When will the Flash Professional CS5 beta be available for download?
The beta will be available for download from Adobe Labs before the end of 2009. How much will Flash Professional CS5 or Creative Suite cost? We are not announcing any pricing at this time. Where can customers go to be notified when the beta is available? You can sign up to be notified: https://www.adobe.com/cfusion/mmfor/index.cfm?name=fpcs5_notify

More information about applications for iPhone
Q: When will Adobe Flash Platform tooling support building applications for iPhone?
A public beta of Flash Professional CS5 including support for building applications for iPhone is planned for later this year. Sign up to be notified when the beta is available.: https://www.adobe.com/cfusion/mmform/index.cfm?name=fpcs5_notify

Q: How does the Flash Platform tooling update help developers?

The tooling update allows developers to use Flash technologies to develop content for iPhone and iPod touch, devices that were previously closed to them. Developers can write new code or reuse existing web content to build applications for iPhone. Because the source code and assets are reusable across the Flash Platform runtimes,—Adobe AIR and Flash Player—it also gives developers a way to more easily target other mobile and desktop environments.

Q: How is this different from Adobe Flash Player 10 coming to iPhone? Will iPhone users be able to view web content built with Flash technology in the iPhone browser?

The new support for iPhone applications in the Flash Platform tooling will not allow iPhone users to browse web content built with Flash technology on iPhone, but it may allow developers to repackage existing web content as applications for iPhone if they choose to do so. Flash Player uses a just-in-time compiler and virtual machine within a browser plug-in to play back content on websites. Those technologies are not allowed on the iPhone at this time, so a Flash Player for iPhone is not being made available today. Flash Professional CS5 will enable developers to build applications for iPhone that are installed as native applications. Users will be able to access the apps after downloading them from Apple’s App Store and installing them on iPhone or iPod touch.

Q: Can applications for iPhone built with Flash Platform tooling be delivered through Apple’s App Store?

Yes. Developers can deliver applications built with Flash Platform tooling just like any other iPhone application. This will require the developer to be a member of the iPhone Developer Program and follow the program guidelines.

Q: Do developers need to participate in Apple’s iPhone Developer Program in order to develop or deploy applications for iPhone using the Flash Platform tools?

Yes. A developer certificate from Apple is required in order to test and deploy applications to iPhone. Apple provides information on its developer programs at http://developer.apple.com/iphone/.

Q: Are applications for iPhone built with Flash Platform tools interpreted at runtime?

No. iPhone applications built with Flash Platform tools are compiled into standard, native iPhone executables, just like any other iPhone application.

Q: Can applications load SWF files or other code at runtime, such as a module from a website?

No. iPhone applications built with Flash Platform tools are compiled into standard, native iPhone executable packages and there is no runtime interpreter that could be used to run ActionScript bytecode within the application.

Q: Which version of the iPhone SDK/operating system is supported by the applications?

Applications can be built targeting iPhone OS 3.0 and later.

Q: Will applications built with Flash Platform tools work on iPod touch? iPhone 1.0? iPhone 3G? iPhone 3GS?

Applications should work on all iPhone and iPod touch devices. However, as the hardware specifications of the devices are widely divergent, content performance may vary between devices and device generations.

Flash Helps Site Launched

Looking for Adobe Flash actionscript 3 helps? Check out: http://dsmith.tv/

Flash Helps: Create Text Field or Text Fields Dynamically

Here’s a simple little example of creating actionscript 3 text fields dynamically.  It is also a great example of using functions to do all the dirty work for you.

In order for this to work you need to put a button component in the library.

This sample will create an input text field instance and a button instance.  When the user click on the button, it will create a new text field and set its x,y to random.

Here is the code:

import fl.controls.Button;
import flash.text.TextField;
import flash.text.TextFieldType;

//create a button
var myButton:Button = new Button();
myButton.label = "set text random x,y";
myButton.emphasized = true;
myButton.width = 150;
myButton.move(50, 100);
addChild(myButton);

var tf1:TextField = createTextField(10, 10, 400, 22, true);
tf1.type = TextFieldType.INPUT;

//create an input text field function
function createTextField(x:Number, y:Number, width:Number, height:Number, border:Boolean):TextField {
     var result:TextField = new TextField();
     result.x = x;
     result.y = y;
     result.width = width;
     result.height = height;
     result.background = true;
     result.border = border;
     addChild(result);
     return result;
}

//event that listens for the button to be clicked
myButton.addEventListener(MouseEvent.CLICK,setRandomXY);

//function that creates the new text field and sets the text
function setRandomXY(e:Event){
     var randomX = Math.random()*stage.width;
     var randomY = Math.random()*stage.height;
     var tf2:TextField = createTextField(randomX,randomY,50,20,false)
     tf2.type = TextFieldType.DYNAMIC;
     tf2.text = tf1.text;
}

Flash Helps: Tile Component

When Flash CS3 came out one of the new components was the Tile Component. The Tile Component in AS3 is similar to the Datagrid component in that it uses columns and rows to render data and images. The Tile Component can come in very useful in many instances of design and implementation.

Flash has a few examples of using the Tile Component in the helps. I’ve taken one of those examples and tweaked it a bit below. I put a text field on the stage with an instance name of myText and created a movieClip on the stage as well with the instance name of myMC.

The actionscript for using the Tile Component is as follows.  You’ll notice that it has some of the same properties as the DataGrid…like I mentioned.

import fl.controls.ScrollPolicy;
import fl.controls.TileList;
import fl.data.DataProvider;
import fl.controls.UIScrollBar;
import fl.events.ScrollEvent;
import fl.controls.ScrollBarDirection;

myText.text = “Select an Image”;

//add a bunch of images and labels
var dp:DataProvider = new DataProvider();
dp.addItem({label:”Image 1″, source:”http://www.helpexamples.com/flash/images/image1.jpg”});
dp.addItem({label:”Image 2″, source:”http://www.helpexamples.com/flash/images/image2.jpg”});
dp.addItem({label:”Image 3″, source:”http://www.helpexamples.com/flash/images/image3.jpg”});
dp.addItem({label:”Image 4″, source:”http://www.helpexamples.com/flash/images/image1.jpg”});
dp.addItem({label:”Image 5″, source:”http://www.helpexamples.com/flash/images/image2.jpg”});
dp.addItem({label:”Image 6″, source:”http://www.helpexamples.com/flash/images/image3.jpg”});
dp.addItem({label:”Image 7″, source:”http://www.helpexamples.com/flash/images/image1.jpg”});
dp.addItem({label:”Image 8″, source:”http://www.helpexamples.com/flash/images/image2.jpg”});
dp.addItem({label:”Image 9″, source:”http://www.helpexamples.com/flash/images/image3.jpg”});
dp.addItem({label:”Image 10″, source:”http://www.helpexamples.com/flash/images/image2.jpg”});
dp.addItem({label:”Image 11″, source:”http://www.helpexamples.com/flash/images/image2.jpg”});
dp.addItem({label:”Image 12″, source:”http://www.helpexamples.com/flash/images/image3.jpg”});

var myTileList:TileList = new TileList();
myTileList.dataProvider = dp;
myTileList.scrollPolicy = ScrollPolicy.ON;
myTileList.columnWidth = 100;
myTileList.rowHeight = 67;
myTileList.setSize(400,67);
myTileList.columnCount = 3;
myTileList.rowCount = 1;
myTileList.move(10, 300);
addChild(myTileList);

myTileList.addEventListener(MouseEvent.CLICK,itemClicked);
function itemClicked(e:Event):void {
//myText
myText.text = myTileList.selectedItem.label;
//myMC
var i =new Loader();
i.load(new URLRequest(myTileList.selectedItem.source));
myMC.addChild(i);
}

Here are the sample files:

tileComponent.swf
tileComponent.fla

Flash Samples: Mini MP3 Music Player in AS3

Here is a little Flash Sample in AS3 ( actionscript 3 ) I made that is a mp3 player.  It looks for a file variable called ‘myURL’ and loads that into the player.

Sample:
http://www.smithmediafusion.com/sotwPlayer.swf?myURL=TheStrokes1251.MP3

Files:
mini MP3 Player.fla

The code uses a flashvar which is the filename / URI of the mp3 file. It also utilizes other Flash Classes including the progressBar, Sound and SoundChannel Classes.

Code:

var myURL = root.loaderInfo.parameters.myURL;

playBtn.visible = true;
pauseBtn.visible = false;
pb.setSize(80.9, 14);
import fl.controls.Label;
import flash.events.Event;
import flash.media.Sound;
import flash.net.URLRequest;
import fl.controls.ProgressBar;
import fl.controls.ProgressBarMode;
myLoadingTxt.text = “Press to play”;
myProgressBar.visible = false;
var sp:Sound;
var songControls:SoundChannel;
var positionPrev:Number;
var mypaused:Boolean;

var t:Timer = new Timer(1000);
t.addEventListener(TimerEvent.TIMER, timerHandler);
function onPlayBtnPress(event:MouseEvent):void {
pb.setSize(80.9, 7);
playBtn.visible = false;
pauseBtn.visible = true;

if(mypaused == true){
trace(“is paused true: “+myProgressBar.value*1000);

songControls=sp.play((myProgressBar.value*1000));
t.start();
mypaused = false;
}else{
myProgressBar.setProgress(0, myProgressBar.maximum);
sp = new Sound();

var req:URLRequest = new URLRequest(myURL);
sp.load(req);

var dataPath:String = myURL;
var loader:URLLoader = new URLLoader();
loader.load(new URLRequest(dataPath));

songControls=sp.play();
songControls.addEventListener(Event.SOUND_COMPLETE,soundCompleteHandler);
trace(“songControls.position: “+songControls.position);
sp.addEventListener(Event.COMPLETE,updateTotalTime);

myProgressBar.visible = true;

myProgressBar.indeterminate = false;
myProgressBar.mode = ProgressBarMode.MANUAL;

addChild(myProgressBar);
var myLabel:Label = new Label();
myLabel.text = “”;
myLabel.autoSize = TextFieldAutoSize.LEFT;
myLabel.move(myProgressBar.x, myProgressBar.y + myProgressBar.height);
addChild(myLabel);

pb.source = loader;
addChild(pb);
myLoadingTxt.text = “Playing…”;

t.start();
}
}
function onPauseBtnPress(event:MouseEvent):void {
pb.setSize(80.9, 14);
playBtn.visible = true;
pauseBtn.visible = false;
trace(“pause”);

positionPrev=songControls.position;
songControls.stop();
mypaused=true;

t.stop();
}

function soundCompleteHandler(event:Event):void {
playBtn.visible = true;
pauseBtn.visible = false;
myProgressBar.visible = false;
mypaused = false;
trace(“done”);
myLoadingTxt.text = “Press to play”;
t.stop();

}

playBtn.addEventListener(MouseEvent.CLICK, onPlayBtnPress);
pauseBtn.addEventListener(MouseEvent.CLICK, onPauseBtnPress);

function updateTotalTime(e:Event):void {

myProgressBar.maximum = sp.length/1000;
trace(“sp.length: “+myProgressBar.maximum);
var minutes=Math.floor((sp.length/1000)/60);
var seconds=Math.floor((sp.length/1000)%60);
//myLoadingTxt.text=((minutes<10)?(“0″+minutes):minutes)+”:”+((seconds<10)?(“0″+seconds):seconds);
}

function timerHandler(event:TimerEvent):void {
myProgressBar.setProgress(myProgressBar.value + 1, myProgressBar.maximum);

}
function stopTimer(event:TimerEvent):void {
trace(“stopped”);
}

Flash Helps: Flashvars in AS3

Another new feature in AS3 ( actionscript 3 ) is the new method of calling and setting flashvars in your actionscript.  Back in actionscript 2, you just call them after setting them in your html code.  AS3 is different.  While there are a few methods to do this, the simplest way I’ve found is this:

//the name of my flashvar is myVar

myText.text = root.loaderInfo.parameters.myVar;

Then you can use the Flash AS3 global variable method I use here to set your flashvar in as3 as a global variable.

MyGlobal.myString =  root.loaderInfo.parameters.myVar;

Flash Helps: AS3 Duplicate Movie Clip

The easiest way to duplicate a movieClip in Flash AS3 that resides in your library is to first create your clip; then, in the library, right click on it and select Linkage…, and finally check the Export for ActionScript check box.

Here’s a step by step in case you got lost while doing the initial steps to duplicate your movieClip using AS3.

1. Create your Clip.  I just made a simple rectangle for an example with a motion tween.

duplicate clip AS3

2. Right Click your clip in the library and select “Linkage…” and then check “Export for ActionScript”.

What this does is make a class called “myMC” that we can now call using actionscript 3.

3.  Put the following actionscript on frame one of your main timeline:

addEventListener(MouseEvent.CLICK,makeABox);

var i:Number = 1; //i will be the total number of boxes

function makeABox(e:Event):void {
trace(“new box #” + i);
var newBox:myMC = new myMC();
addChild(newBox);
newBox.x = stage.mouseX;
newBox.y = stage.mouseY;
i++;
}

So what this all means is, we use addEventListener to listen for a mouse click.  When a mouse click is detected, it runs the function makeABox.  This function calls our new class “myMC” and adds a new child clip using addChild.  We set the X and Y of the clip by detecting the X and Y of the mouse on the stage.

Here’s a screen shot:

Flash AS3 helps duplicateMovie

Here are the source files, happy flash actionscript 3 – ing:

duplicateMovieAS3.fla

duplicateMovieAS3.swf

Flash Help: AS3 Anchor Object to a Point

Here’s a little helpful Flash AS3 sample that connects two object using Flash Actionscript 3.  Drag either of the objects (the green point or the cloud popUp) and they’ll stay connected.  Something like this might come in handy for a Flash map point sort of a thing or you could even motion tween the green point and have the popUP stay in the same place. This also uses the ENTER_FRAME eventListener method that calls graphics.lineTo and graphics.beginFill on frame enter.

Here’s the actionscript:

import flash.display.Shape;
import flash.display.Sprite;
import flash.display.Graphics;

//drag the two objects on the stage popup and myPoint
popup.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
function mouseDown(event:MouseEvent):void {
popup.startDrag();
}

popup.addEventListener(MouseEvent.MOUSE_UP, mouseReleased);
function mouseReleased(event:MouseEvent):void {
popup.stopDrag();
}

myPoint.addEventListener(MouseEvent.MOUSE_DOWN, pointMouseDown);
function pointMouseDown(event:MouseEvent):void {
myPoint.startDrag();
}

myPoint.addEventListener(MouseEvent.MOUSE_UP, pointMouseRelease);
function pointMouseRelease(event:MouseEvent):void {
myPoint.stopDrag();
}

//draw the connecting shage
var triangle_mc = new Shape();
addChild(triangle_mc);

popup.addEventListener(Event.ENTER_FRAME,popUPEnter);
function popUPEnter(evt:Event) {

triangle_mc.graphics.clear();
triangle_mc.graphics.beginFill(0xFFFFFF,100);
triangle_mc.graphics.lineStyle(4,0xFFFFFF,100);
triangle_mc.graphics.moveTo(myPoint.x,myPoint.y);

triangle_mc.graphics.lineTo(myPoint.x,myPoint.y);

if (popup.y<myPoint.y) {

triangle_mc.graphics.lineTo((popup.x),(popup.y+40));
triangle_mc.graphics.lineTo((popup.x),(popup.y+80));
triangle_mc.graphics.endFill();
}
if (popup.y>myPoint.y) {

triangle_mc.graphics.lineTo((popup.x),(popup.y));
triangle_mc.graphics.lineTo((popup.x),(popup.y)+30);
triangle_mc.graphics.endFill();
}
}

Here are the source files:
anchorTest – AS3.fla
anchorTest – AS3.swf

Flash Helps: onEnterFrame in AS3 is Event.ENTER_FRAME

I have many fond memories of onEnterFrame in actionscript 2…so many I that I really don’t recall. I’d slap my movieClip instance on the stage and put onEnterFrame on there and I could call the same actionscript over and over again all day long.

With object oriented programing and actionscript 3 onEnterFrame is now Event.ENTER_FRAME.  So it essensitially does the same thing.  Since it is an event it is located in the Event class. Here’s a little snippet:

myMC.addEventListener(Event.ENTER_FRAME,myMCEnterFrame);
function myMCEnterFrame(evt:Event){

trace(“this is myMC”); //traces ‘this is myMC’   over and over

};

Pretty simple and straight forward.

Flash Snow Flakes in AS3

Here’s a little seasonal fun using Flash AS3 to create some falling snow flakes for your holiday enjoyment.

First you need to create the falling flake which will be dynamically duplicated.  Here’s a little snap of my flake:

The flake is tweened and follows the guide downward.  I also added some rotation to the tween.

Next, you’ll need the duplication script which does all the work:

//number of flakes
var myFlakes = 200;
//size of flakes
var mySize = 2.2;

function dupFlakes(target:DisplayObject, autoAdd:Boolean = false):DisplayObject {

var targetClass:Class = Object(target).constructor;
var duplicate:DisplayObject = new targetClass();

duplicate.transform = target.transform;
duplicate.filters = target.filters;
duplicate.cacheAsBitmap = target.cacheAsBitmap;
duplicate.opaqueBackground = target.opaqueBackground;

if (autoAdd && target.parent) {
target.parent.addChild(duplicate);
}
return duplicate;
}

for (var i=0; i<=myFlakes; i++) {
var r = Math.round(Math.random()*100);
var myCopiedSprite:MovieClip = dupFlakes(flake_mc,true) as MovieClip;
var myNum = Math.round(Math.random()*550);
myCopiedSprite.x = Math.round(Math.random()*1000);
myNum = Math.round(Math.random()*mySize);
myCopiedSprite.scaleX += myNum;
myCopiedSprite.scaleY += myNum;
myCopiedSprite.gotoAndPlay(r);
}

The code duplicates our desired number of flakes and sets the size.  Since we don’t want all the flakes to fall simutaniously, we need to tell them to start at different times. Hence, the gotoAndPlay at a random point in the flakes path.

Here’s a snap of the finished product:

Mess around with it and happy holidays!

the files:
fallingSnowAS3.fla

fallingSnow.swf

Adobe Flash CS4 Professional Classroom in a Book (Paperback)

 I just found this great book on Flash CS4.  I recommend that you check it out and get yourself a copy.

The fastest, easiest, most comprehensive way to learn Adobe Flash CS4 Professional.

Adobe Flash CS4 Professional Classroom in a Book contains 10 lessons. The book covers the basics of learning Adobe Flash CS4 Professional and provides countless tips and techniques to help you become more productive with the program. You can follow the book from start to finish or choose only those lessons that interest you.

Learn how to design Flash projects with sophisticated animation, import video and sound files, and integrate buttons with compelling interactivity using ActionScript 3.0. Powerful features such as the new Motion Editor, inverse kinematics, and support for 3D will make developing your Flash sites fast, easy, and fun.

“The Classroom in a Book series is by far the best training material on the market. Everything you need to master the software is included: clear explanations of each lesson, step-by-step instructions, and the project files for the students.” —Barbara Binder, Adobe Certified Instructor, Rocky Mountain Training

Classroom in a Book®, the best-selling series of hands-on software training workbooks, helps you learn the features of Adobe software quickly and easily. Classroom in a Book offers what no other book or training program does—an official training series from Adobe Systems Incorporated, developed with the support of Adobe product experts.

Get a Copy Here >

Flash AS3 _global or root variables

Flash actionscript 2 was great for _global or root variables or values.  With actionscript 3 ‘_global’ and ‘root’ are not longer valid markup.  Since AS3 is object oriented scripting, those methods of assigning values are no longer valid.  So, the question is: how do I use global or root variables in Flash AS3 (actionscript 3). Here is a method that I use on projects where I need to have a work around and utilize a variable that will be called in multiple functions across the timeline.

First, I create an actionscript file (.as) with my variable names and their types declared within a class, in this case I called my class ‘MyGlobal’.

package {

public class MyGlobal {

public static var myTotal:int;
public static var myArray:Array = new Array();
public static var mySting:String = new String();
}

}

Save this file as ‘MyGlobal.as’.

Next, create a new Flash file (.fla) and save it in the same location as the MyGlobal.as file. When we create our swf file the .as file will be compiled.

In the .fla file we need to import our class that we have created.

import MyGlobal;

Now we can assign values to these variables within the .fla file and utilize them anywhere.  Just remember to use the class name MyGlobal in front of the variable name in the constructor.

MyGlobal.myTotal = 22;

MyGlobal.myArray.push(“value1″);
MyGlobal.myArray.push(“value2″);
MyGlobal.myArray.push(“value3″);

MyGlobal.myString = “this is a string”;

That’s it.  Global variables are alive and well in Flash AS.  Have fun!

« Previous Entries