A way to quick fill a FlxTypedGroup?

44 views
Skip to first unread message

JohnD

unread,
May 17, 2015, 3:42:58 PM5/17/15
to haxef...@googlegroups.com

I use many FlxTypedGroups as object pools in my project, for bullets,particles, explosions,etc.

And everytime I create one, I seem to use the same 4-5 lines of code to init them and fill them with the objects. 
I was wondering if there is a way to share that functionality and use something like:

var pool_bullets:FlxTypedGroup<Bullet> = createPool(Bullet,20);

createPool should return a new FlxTypedGroup<Bullet> object filled with 20 Bullet, instances.

Haxe seems like a powerful language, but I can't seem to get into some of the more advanced features, like these kind of generics.

thanks!



JohnD

unread,
May 17, 2015, 3:49:20 PM5/17/15
to haxef...@googlegroups.com
All I've come up with is this:

public static function createPool<T>(size:Int):FlxTypedGroup<T>
{
var pool = new FlxTypedGroup<T>();
var r1 = size;
pool.maxSize = size;
do {
pool.add(new T()).kill();
}while (--r1 >= 0);
return pool;
}

But the HAXE compiler complains 
Only generic type parameters can be constructed

Gama11

unread,
May 17, 2015, 4:41:18 PM5/17/15
to haxef...@googlegroups.com, dropdat...@gmail.com
new T() isn't type-safe and thus can't work. Haxe doesn't know what the constructor for those classes looks like, they could have required arguments.

You can do this in a non-type-safe manner by assuming that each class you use the function for has the same constructor arguments using Type.createInstance(). That function requires a Class<T>, for example "Bullet" from your initial example. 
Reply all
Reply to author
Forward
0 new messages