Archive for the ‘Tips’ Category

This isn’t right… MovieClip nested inside Button throwing null object reference error in Flash CS4

Thursday, September 10th, 2009

A great thing about teaching is that your students approach problems in ways you haven’t done before and run into problems that you never knew existed. This is one such problem in Flash CS4 and a curious one at that.

THE PROBLEM: A Button symbol is placed on the Stage on a frame other than the first frame and given an instance name in the Properties panel. In the Actions panel, ActionScript is added that references the instance name of the button on the same frame that the button instance first appears on. The movie is tested and the following error occurs:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at MovieClipInsideButton_fla::MainTimeline/frame2()

Normally this error means that a particular instance has not been given an instance name in the Properties panel on the frame where the ActionScript appears. However, nothing looks amiss in the ActionScript or on the Stage. Adding a trace statement, such as trace(myButton); reveals null in the output window, meaning the trace statement has run before the instance name has been set to the button instance on the Stage. Hmm… very perplexing, since you may have other buttons and movieclips that work fine when referenced from ActionScript.

THE SOLUTION: From what I found, one scenario will produce this error. If a MovieClip symbol (instance) appears inside a Button symbol and the button appears on any frame other than the first frame, and the frame where the ActionScript references it is the same frame it first appears on—then this behavior will result.

MC_inside_button

There are a few workarounds:

  1. Retrieve the instance from the display list of its parent. Instead of referencing the Button instance on the stage directly, use getChildByName(.) to retrieve a reference to the instance, this can even be set to instance name at the beginning of your timeline code, like so:
    // myButton is the name of the instance as set in the Properties panel.
    // Retrieved child is cast as a SimpleButton, since this is the 
    // class of the Button symbol
    myButton = SimpleButton(getChildByName("myButton"));
  2. Do not nest a MovieClip inside a Button symbol. A Button nested inside a Button, a MovieClip nested inside a MovieClip, and a Button nested inside a MovieClip work fine.
  3. Place the first occurance of the Button instance on any frame before the frame where ActionScript first references it. This behavior appears to indicate Flash is taking too long to parse over the MovieClip inside a Button and runs the ActionScript on the timeline prematurely. Having the instance appear on a frame prior to the frame the ActionScript appears on ensures the instance is completely present in memory before it is referenced.
  4. Place the instance referencing code inside an enter frame event handler function. To ensure the entire frame has been parsed before any ActionScript code is run, enclose the offending code inside the event handler function of the enter frame event, and only make it run once, like so:
    addEventListener( Event.ENTER_FRAME , ensureRendered );
     
    function ensureRendered( evt:Event ) : void
    {
    	removeEventListener( Event.ENTER_FRAME , ensureRendered );
    	// All instance referencing code appears below this point
    	// In this case, instance is named "myButton" on the Stage
    	myButton.width = 200;
    }

This behavior doesn’t seem right to me and even seems it could be a bug. If anyone has an explanation for this behavior, I would love to hear it. You may download an example FLA here: Download Source

UPDATE September 20, 2009: I added a new workaround, which is probably the most succinct and reliable one yet to use. See Retrieve the instance from the display list of its parent in the list of workarounds.

Creating a date countdown timer in ActionScript 3 / Flash

Monday, August 3rd, 2009

Creating a countdown timer in ActionScript is quite easy. The essentials of it are:

  1. Specify a target date to countdown to using the Date class.
  2. Create a Timer instance to check the countdown time each second or so.
  3. At each tick of the timer calculate the number of milliseconds between now and the target date.
  4. Determine how many days, hours, minutes, seconds, etc. that number of milliseconds is equal to.
  5. Update the graphics to reflect the amount of time left.

The following is an example of a countdown timer, with a link to the source code below. This utilizes a reusable class file for the countdown timer. All code specific to this particular implementation can be found in com/anselmbradford/Main.as.

This movie requires Flash Player 9

Download Source

Object-Oriented JavaScript Tip: Implementing the Singleton Pattern

Tuesday, April 21st, 2009

The Singleton design pattern is a development approach that ensures only a single instance of a particular class is available in a system. Imagine building the game of chess, you would only want there to be one instance of the board floating around—say an instance of a class called ChessBoard. The Singleton pattern ensures that there will only ever be one ChessBoard object available in your game.

Often the implementation of a Singleton looks something like this:

function Singleton()
{
}
 
Singleton.getInstance = function( )
{
	if (Singleton.instance == undefined) Singleton.instance = new Singleton();
	return Singleton.instance;
}

However, this is a port to JavaScript from other languages and it doesn’t offer a very robust implementation of the Singleton. For example, this design relies on calling Singleton.getInstance() to retrieve the single instance. However, nothing prevents calling…

var instance1 = new Singleton();
var instance2 = new Singleton();
alert( instance1 == instance2 ); // outputs false because these are two object instances

…to create two instances, defeating the pattern. A better approach is to encapsulate the Singleton constructor function in a variable and return a reference to the function rather than the instance, and then provide access to the instance via a getInstance method as above.

var Singleton = new function Singleton() 
{
	var instance = this;
	Singleton.getInstance = function()
	{
		return instance;
	}
}

In this case, the code shown earlier does not break the pattern:

var instance1 = new Singleton();
var instance2 = new Singleton();
alert( instance1 == instance2 ); // outputs true because these refer to the same constructor function

However, this just prevents circumvention of the pattern, the same object instance has not yet been retrieved. To do this the static getInstance() method is called on the constructor reference variable.

var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
alert( instance1 == instance2 ); // outputs true because these refer to the same object instance

Additionally, a toString method, as well as static and instance methods (though both are functionally identically in this case since there’s only one instance available) can be built into the Singleton definition, like so:

var Singleton = new function Singleton() 
{
	var instance = this;
	Singleton.getInstance = function()
	{
		return instance;
	}
	this.toString = function()
	{
		return "[object Singleton]";
	}
 
	this.instanceMethod = function()
	{
		alert( "instance method called!" );		
	}
 
	Singleton.staticMethod = function()
	{
		alert( "static method called!" );
	}
	return Singleton;
}

Try these out:

Singleton.staticMethod();
Singleton.getInstance().instanceMethod();

Since JavaScript is a prototype-based language (not actually having classes), additional functionality can be added through the Singleton’s prototype, as in:

Singleton.prototype.custFunct = function(){ alert( "A custom method" ); } // add instance method
Singleton.getInstance().custFunct(); // call new instance method

Object-Oriented JavaScript Tip: Creating static methods, instance methods

Thursday, April 9th, 2009

Custom JavaScript objects can have instance methods (function that are associated with a particular JavaScript object), but like other Object-Oriented languages, they can also have static methods, that is functions that are associated with the JavaScript class that created an object, as opposed to the object itself. This is useful in cases where a function (a.k.a. a method) will not be different in different object instances. Let’s look at an example…

Suppose you created a class to handle simple arithmetic calculations:

function Calculator()
{
 
}

To begin with, an instance method could be added to this class in one of two ways, either inside the constructor or through the class prototype. In this example, one method called multiply will be created, which returns the product of two values multiplied together. First, implemented in the constructor it looks like:

function Calculator()
{
	this.multiply = function(val1 , val2)
	{
		return (val1*val2);
	}
}

Via the class prototype, which is a more readable solution in my opinion, it would look like:

function Calculator()
{
}
 
Calculator.prototype.multiply = function(val1 , val2)
{
	return (val1*val2);
}

Use of this method would then occur through instances of the Calculator class, like so:

var calc = new Calculator();
alert( calc.multiply(4,3) ); //pop-up alert with product of 4 times 3

However, it shouldn’t really be necessary to create an object to use the multiply method, since the method isn’t dependent on the state of the object for its execution. The method can be moved to the class to clean up this code a bit. First the class definition is created, which looks almost identical to the instance method declaration above, with the exception of the prototype keyword being removed:

function Calculator()
{
}
 
Calculator.multiply = function(val1 , val2)
{
	return (val1*val2);
}

Now the multiply method can be called through the class itself, instead of an instance of the class, like so:

alert( Calculator.multiply(4,3) ); //pop-up alert with product of 4 times 3

Object-Oriented JavaScript Tip: Overriding toString() for readable object imprints

Sunday, April 5th, 2009

JavaScript has a core Object class that contains a toString() method that is called whenever a request is made to convert an object to a string (like related ECMAScript-based ActionScript). This is often done during debugging to check that a variable actually contains a reference to a certain object.

Most likely alert(myObj) or console.log(myObj) would be used, for example:

var myObj = new Object()
alert(myObj); // popup displays [object Object]

The problem is if you create a custom object. In this case it would be ideal to adjust the string representation to reflect the fact that the custom object is different from the core object. By default there is no difference, as the following example demonstrates:

// custom Foo class
function Foo() 
{	
}
 
// new Foo object instance
var f = new Foo();
alert(f);  // popup displays [object Object]

To make this more readable, add a toString() method to the prototype of the object:

function Foo() 
{
}
 
// toString override added to prototype of Foo class
Foo.prototype.toString = function()
{
	return "[object Foo]";
}
 
var f = new Foo();
alert(f);  // popup displays [object Foo]

In this case, because of the presence of the toString() method, which overrides the default, a custom string can be displayed for the object that is more applicable to what it is. Additionally, information about the properties of the object could be included in this method as well, as in:

function Foo() 
{
	this.message = "Hello World!";
}
Foo.prototype.toString = function()
{
	return "[object Foo <" + this.message + ">]";
}
 
var f = new Foo();
alert(f);  // popup displays [object Foo <Hello World!>]

Common Flash Compiler Errors: #1046

Wednesday, March 25th, 2009

This error shows the following in the Compiler Errors window:


1046: Type was not found or was not a compile-time constant: [Class name].

Quick Answer and Solution

Where I have “[Class name]” above you will have any number of names listed, for example it may say Event, Sprite, TextField, etc. What this means is you are using a piece of code that utilizes a class (typically seen as files with a “.as” extension) that you have not “imported” so that your code knows where to find it. To fix this problem perform the following:

  1. Open a web browser and navigate to Google.
  2. Enter the search “[class name] actionscript 3 site:livedocs.adobe.com” (replacing [class name] with whatever the class name is in the error message, such as TextField, MouseEvent, URLLoader, etc.). For example, “Event actionscript 3 site:livedocs.adobe.com”
  3. Look for a search result that lists the class in a format of a series of words with dots between them, probably will be the top result. Examples include:
    • flash.events.Event
    • flash.display.Sprite
    • fl.transitions.Tween
    • flash.geom.Rectangle

    This is the path to the class, which you can use to import the class into your code.

  4. Without clicking on the search result, copy the class name as it appears in the previous step.
  5. Return to Flash and double-click the error message.
  6. Scroll to the top of the code area. Type “import” and paste the path to the class. For example,
    import flash.events.Event;

If you are using code on the Timeline, this can be placed at the top of the Actions panel. If you have written a class file that is referencing another class, this code appears between the package { curly brace, and class declaration, public class MyClass.

For example,

package
{
	// class import statements appear here
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
		}
	}
}

Technical Overview

A class file is an external text file that contains variables and functions (known as properties and methods in the object-oriented programming context), essentially this means class files are self-contained blocks of code that contain code related to a particular task. To access these variables and functions within your own block of code the class file needs to be imported. If your code contains any references to a class file that has either: (a) not been imported, or (b) is not within the same folder as your .fla or .as files, then a #1046 error will be thrown. For example, suppose you have the following class file declared for a button:

package
{
	import flash.display.MovieClip;
 
	public class MyButton extends MovieClip
	{
		public function MyButton()
		{
			this.addEventListener( MouseEvent.CLICK , _clicked );
		}
 
		private function _clicked( evt:MouseEvent ) : void
		{
			// button was clicked!
		}
	}
}

Testing this code would produce the following error:

1046: Type was not found or was not a compile-time constant: MouseEvent.

With the source listed as…

private function _clicked( evt:MouseEvent ) : void

This is because the class MouseEvent is referenced in the code, but is not imported at the top of the class file. The fix is simple and looks like this:

package
{
	import flash.display.MovieClip;
	// import the MouseEvent class
	import flash.events.MouseEvent;
 
	public class MyButton extends MovieClip
	{
		public function MyButton()
		{
			this.addEventListener( MouseEvent.CLICK , _clicked );
		}
 
		private function _clicked( evt:MouseEvent ) : void
		{
			// button was clicked!
		}
	}
}

Typically if you are a beginning ActionScripter, you will run into this error when referencing classes created by Adobe. However, as you become more advanced in your scripting abilities you may place your own custom class files in “packages” that would then need to be imported using the same above process. In case you are wondering what the stuff is before the actual class name, such as “flash.display” and “flash.events,” this is the “package” that class resides in, which is essentially the folders the class file resides in on disk. For example, suppose I created a class called “MyButton” and placed it in the package “com.anselmbradford.” This class would appear in a text file called “MyButton.as” that would be in a folder called “anselmbradford” that would itself be in a folder called “com.” The class file would look like:

package com.anselmbradford
{
	import flash.display.MovieClip;
 
	public class MyButton extends MovieClip
	{
		public function MyButton()
		{
		}
	}
}

To import this class file into another class file I would place the “com” folder (containing the class file two levels in) in the same directory as my .fla or .as file that I wanted to import this class into. I would then import it using the syntax shown previously. For example:

package
{
	import flash.display.MovieClip;
	// class is imported
	import com.anselmbradford.MyButton;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
			// class is referenced in code, so must be imported
			var button:MyButton = new MyButton();
		}
	}
}

Note: Whole sets of class files that are within the same package can be imported using the “*” wildcard operator. For example, flash.events.Event, and flash.events.MouseEvent, both reside in the flash.events package. Instead of having two lines to import both of these classes, you can have import flash.events.*;, which will import all the necessary classes from the flash.events package.

UPDATE October 4, 2009:This error will also occur if you have a symbol on your stage that has an instance name that is the same as a class name associated with the symbol. Check the Library panel, under the Linkages column, does any of your symbols have a name next to “Export:” that is the same as the instance name in the Properties panel of one of those symbols on the stage?

type_error

Common Flash Compiler Errors: #1042

Thursday, March 19th, 2009

This error shows the following in the Compiler Errors window:


1042: The this keyword can not be used in static methods. It can only be used in instance methods, function closures, and global code.

Quick Answer and Solution

Most likely you are you using the keyword “this” inside a class file, but it is not inside the curly braces of a function. By double-clicking on the error it will take you to the offending line of code. Check carefully to make sure where you have placed the keyword “this” is actually between the opening “{” and closing “}” braces of a function declaration. If it looks correct, but is accompanied by error #1126 (described here), then fix that error first. Also, if the “this” keyword appears in a function that has the “static” keyword in its declaration, error #1042 will also be thrown.

The following are three scenarios where a class file will throw this error:

package
{
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
		}
		// "this" keyword used outside a function
		this.visible = false;
	}
}
package
{
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
		}
 
		// function does not have a body because of misplaced semicolon,
		// so error #1126 is thrown
		public function hide():void;
		{
			// the "this" keyword is actually not in the body of a function
			// because of the above #1126 error
			this.visible = false;
		}
	}
}
package
{
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
		}
 
		// function is a "static method," meaning it runs inside the class,
		// not the object created from the class
		static public function hide():void
		{
			// the "this" keyword is inside a static method
			this.visible = false;
		}
	}
}

The corrected form of the above examples would be:

package
{
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
		}
 
		public function hide():void
		{
			// the reference to "this" is inside a non-static function
			// (called an instance method)
			this.visible = false;
		}
	}
}

Technical Overview

There are two types of methods (functions) that can appear in a class file, static methods and instance methods. Static methods refer to methods that are run via the class itself, while instance methods refer to methods run via an instance of the class. Consider the following class file:

package
{
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main()
		{
		}
 
		static public function staticMethod():void
		{
			trace( "static method called!" );
		}
 
		public function instanceMethod():void
		{
			trace( "instance method called!" );
		}
	}
}

To call the first method, a new “Main” object does not need to be created, as the static method can be called on the class itself, like so:

Main.staticMethod();

Conversely, to access the other method, an (object) instance of the Main class needs to be created and then the method can be called through that object, like so:

var main:Main = new Main();
main.instanceMethod();

Use of the “this” keyword refers to the object instance of the class that the code is currently dealing with (in the above case if this appeared in the body of the instanceMethod() method it would be referring to the object placed in the main variable). Since no object instance has to be created to use static methods, the “this” keyword can not be used within those methods because there is no object in existence to refer to. Additionally, all code outside of a function declaration runs before an object instance is created (before the constructor function runs), so any references to “this” do not have an object to refer to in that context either.

2 invaluable Drupal development tips: list all available variables and backtrace a page

Saturday, March 14th, 2009

The Drupal Devel module includes some invaluable functions that make working with Drupal much much easier. A short list of these functions can be found at this post. One of these is the dpm() command (which I would guess stands for “Drupal Print Message,” or at least that’s how I remember it). Given an array or object, this function will output a div structure at the top of your page that you can use to visually walk through the contents of either of these sets of data. Combine this with existing PHP debugging and instrospection commands and you have a very useful and powerful development tool at your disposal. For example, place this at the top of your Drupal theme’s page.tpl.php template:

<?php
	 dpm( get_defined_vars() );
?>

Now when you navigate to your page you will have a clickable bar at the top that will list all variables available to the page when it loads, which you can access via the code in your theme page template if you want.

dpm_get_defined_vars

Or maybe you would like to know what path your page took through Drupal’s architecture to its final incarnation, use dpm() with PHP’s debug_backtrace() function. This will output an array of each function your page contents went through before they were output to the browser, plus it shows the location of these functions. Try this in place of the code snippet above:

<?php
	 dpm( debug_backtrace() );
?>

dpm_debug_backtrace

Common Flash Compiler Errors: #1126

Friday, March 13th, 2009

This error shows the following in the Compiler Errors window:


1126: Function does not have a body.

Quick Answer and Solution

By double-clicking on the error it will take you to the offending line of code. This error commonly happens when the end of line designator “;” is placed at the end of a function name declaration, as in:

1
2
3
4
function init() : void;
{
	/*function body*/
}

Notice the presence of the semicolon at the end of line 1. To fix the error the semicolon is removed:

1
2
3
4
function init() : void
{
	/*function body*/
}

Technical Overview

A function is a block of code that will only run when it is “called,” meaning the above example would be run by writing the function name elsewhere, like so: init();. When a particular function is called, the code that appears between the curly braces (“{}”) is run. This is referred to as the function “body.” When you test a movie in Flash the code is read line by line by the compiler and eventually turned into a SWF. However, what you see as a single line of code and what the compiler sees as a single line of code are two different things. The compiler ignores extra white space and carriage returns. For example, to the compiler the following function declaration:

function init() : void
{
	/*function body*/
}

…is the same as:

function init():void{/*function body*/}

Because of this, it depends on the semicolon and closing curly brace (“}”) to denote that a line of code has ended. The closing curly brace is used for every piece of code that creates a block of code (functions, for example), while the semicolon is used for everything else. If a semicolon were to appear before the opening curly brace (“{“) in the above line of code, the compiler would hit the semicolon and throw an error that the function did not have a “body” because it had reached the end of the line of code without encountering an opening and closing curly brace.

Note: The one exception to this rule is the constructor function found in class files, which can oddly enough contain a semicolon after the function name declaration and the compiler will not complain, for example the following will not throw an error:

package
{
	import flash.display.MovieClip;
 
	public class Main extends MovieClip
	{
		public function Main();
		{
			/*constructor function body*/
		}
	}
}

However, while the compiler will not complain, the constructor function actually ends at the semicolon, so what’s written between the curly braces (the “constructor function body”) will not be run when a new object of this class is instantiated (well, actually it will run, but it will be in the scope of the class, not the object, so it will run prior to the creation of the object). Constructor functions are different in one other aspect as well, they do not specify a return type (no “:void” after the parentheses, for example).

Common Flash Compiler Errors: #1009

Thursday, February 26th, 2009

My students often run into the same kinds of errors, so I thought I would post some info on the more common ones. One very common error to receive in Flash is this one:


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

Quick Answer and Solution

Somewhere in your code there is a variable that you are using to refer to a property or method of an object (such as a movie clip), however, it does not actually contain an object so it throws an error. Look for the parts of your code where you have a dot following a variable name and some property or method, such as myMC.width or myMC.startDrag(). Place a trace statement above this variable to see if its value is null.

 
trace( myMC );
// if this lists "null" in the output window the next line of code will throw an error
// look for the first occurrence of myMC (where it was created) to see why it does not 
// contain a reference to something other than null
myMC.width = 200;

Technical Overview

Objects are collections of variables and functions that are defined in a class file. In the context of Object-Oriented Programming, variables are referred to as properties, and functions are referred to as methods. A movie clip object (which is an instance of the MovieClip class) contains properties and methods for dealing with the appearance and interactivity of movie clips, such as x, y, width, height, startDrag(), addEventListener(.), etc. When a new object is created it is typically stored in a variable—technically meaning a reference to the object is stored in the variable, not the actual object—the variable acts like a unique identifier to lookup the object within a particular section of code (called the scope of the variable).

For example, a new movie clip object can be created with new MovieClip(), this would then be stored in a variable (named myMC in this example) with the code var myMC:MovieClip = new MovieClip();. Properties and methods of this movie clip object can be accessed using dot notation. For example, to return the width in pixels of the movie clip, the following may be typed:

var myMC:MovieClip = new MovieClip();
trace( myMC.width );
// outputs 0 because the movie clip doesn't have any graphics, 
// and is therefore 0 pixels wide

If the variable was created, but not set to reference a new movie clip object instance, it will be empty and contain the special value of null, denoting the absence of a reference to an object. Trying to access a property or method via the variable would then mean the computer would attempt to find the property or method of a null value, which being a placeholder for “no value,” throws an error.

var myMC:MovieClip;
trace( myMC.width );
// throws error #1009 because the variable myMC does not contain a reference to an object