Libgdx 个不同类型的子对象池

Libgdx pools for different types of childs objects

我有一个单位 class 和它的一些子单位class(弓箭手、剑客等)。 我怎样才能创建一个池来回收所有那些类型为 unit 的子classes?

这是不可能的,因为 Pool 只能包含一种特定类型的对象。否则你可能会遇到这样的事情:

Pool<Unit> unitPool = ...;
Archer acher = new Archer();
unitPool.free(archer); // we free an Archer, who is a Unit
Unit swordsmanUnit = unitPool.obtain(); // we can obtain only Units
Swordsman swordsman = (Swordsman) swordsmanUnit; // This is actually an Archer and will result in a ClassCastException

幸运的是,libgdx 带有一个名为 Pools 的实用程序,可以轻松汇集许多不同的 classes。它从正确的池中为每个 class 和 frees/obtains 对象创建一个 ReflectionPool。只需让您的 Unit class Poolable.

Archer archer = Pools.obtain(Archer.class);
Swordsman swordsman = Pools.obtain(Swordsman.class);
// ...
Pools.free(archer);
Pools.free(swordsman);