Stroep

Just a collection of random works – Mark Knol

Quick post here. I’d like to share this very quick way to create an automatic ID or index to your class instances. Mostly I pass an index as parameter to the class instance, or I use a public var to set the index. Using this way it is very easy to create an automatically filled index, since you have to set this up once and never worry again :)

Take a look at this code:

package
{
  public class MyObject
  {
    private static var global_index:int = 0;
    public const INDEX:int = global_index ++;
  }
}
 

As you see, I have created a static variable global_index, which is always the same to all MyObject classes. I also created a public constant ‘INDEX’, which would be unique in every instance. When the MyObject instance is created the index will be set to the global_index, and the global_index will increase by one. So that’s basically the trick to create the auto-increment index for your AS3 class.

update: Changed global_index to a private static + removed constructor


2 responses to “Quick way to create an auto-increment index AS3”

  1. You can leave out the constructor, too.

Say something interesting

Please link to code from an external resource, like gist.github.com.