Creating Custom Methods in ActionScript 3

February 9, 2008 by jared 

Click here to download the sample files.

Methods are simply functions inside a class. Think of a class as an object, lets say a car engine.

Car picture

So here’s the basic setup for a Car engine class object in ActionScript 3. (CarEngine.as)

Open up CarEngine.as. Here we have a class named CarEngine.

Inside the class we have declared a boolean (boolean returns either a true or false value) variable called _engineStatus to check the status of the car engine.

public class CarEngine extends MovieClip {

     private var _engineStatus:Boolean;

     public function CarEngine() {

Inside the constructor (code inside the constructor is executed immediately when the class is initialized) we find the following

_engineStatus = false;trace("Car's engine is currently " + this._engineStatus);

What these two lines do is first declare the _engineStatus (that we declared earlier as a boolean variable) as false, and send a trace statement to return the current value of the car engine.

The next two functions enables the CarEngine class to “get” and “set” the current status of the engine.

public function get engineStatus() {
     return _engineStatus;
}
public function set engineStatus(value) {
     _engineStatus = value;
}

Now all that’s left is to call this class from an external source. Open up Car.fla, click on the first frame and press F9 on your keyboard. It should open up the actions panel and you should see some code in there.

The first line initializes an instance of the Car Engine class.

var _carEngine:CarEngine = new CarEngine();

As mentioned above, code inside the constructor is executed immediately when the CarEngine class is initialized. Therefore it should return us a trace statement in the output window, telling us that the engine is currently false.

Now lets modify the engine status and change it to true.

_carEngine.engineStatus = true;

And finally lets check if the engine is now true

trace("Car's engine is changed to " + _carEngine.engineStatus);

And it is!

Click here to download the sample files.

Comments

Feel free to leave a comment...
and oh, if you want a pic to show with your comment, go get a gravatar!