Date: Thu, 23 May 2013 11:31:06 +0200
Quote:
- Casual Game Development
Reinitializing an Instance
http://blog.pettomato.com/?p=19
Text:
-
class SomeClass{
-
public var Initialize:Function = SomeClass; // points to the constructor.
-
public var someProperty:Number;
-
public function SomeClass(arg1){
-
someProperty = arg1;
-
}
-
}
-
var a = new SomeClass(3);
-
trace(a.someProperty); // 3
-
a.Initialize(7);
-
trace(a.someProperty); // 7
-
Occasionally, I want to reuse an object without having to create a new instance from scratch. Creating an instance with the new operator can be prohibitively expensive if you have to do it a lot. For example, I'm working on a project where a firework explodes into several dozen sparks. If I was to create that many new instances at the same time, the game would stick on that frame for too long. After testing a variety of convoluted solutions, I discovered that the answer is actually quite simple.
Example Class
Now, I have created a new variable that points to the constructor function. By calling Initialize(), I can re-run the constructor without having to create a new instance. As long as all the member variables are initialized in the constructor, the object should be good as new.
Example Usage
This solution works best if you can maintain a pool of instances, and grab a free instance when you need it. For my firework project, I create around 200 sparks up front because I know that is the maximum that I will ever use at one time. Then, instead of creating and deleting sparks during the game, I just borrow them from the pool and return them when I'm done.
Via FeedShow.com