I’m trying to implement object pooling on A* nodes, but when I put in the object pooling code, the pathfinding is unable to find a path. From what I can figure out, the pooled nodes are not being fully cleaned before being pulled from the pool, and the pathfinding is suffering because of this.
Here is a trimmed down version of my class, with the pooling code.
public class ShippingRouteNode : IAStarNode {
// either "node" or "line" currently, but making it as a string to potentially support modding
public string Type;
// only non-null if type is transitline
public TransitLineScript TransitLine;
// machine readable name for the transit type in use
public string TransitTypeKey;
// only non-null if type is node
public TransitNodeScript Node;
private ShippingRouteNode() {
}
private static Queue<ShippingRouteNode> _nodePool;
public static ShippingRouteNode FromPool() {
ShippingRouteNode node;
if (_nodePool == null) {
_nodePool = new Queue<ShippingRouteNode>();
}
if (_nodePool.Count == 0) {
node = new ShippingRouteNode();
} else {
node = _nodePool.Dequeue();
}
return node;
}
public static void ToPool(ShippingRouteNode node) {
node.Type = "";
node.TransitLine = null;
node.TransitTypeKey = "";
node.Node = null;
_nodePool.Enqueue(node);
}
public static void ToPool(IEnumerable<ShippingRouteNode> nodes) {
foreach (var node in nodes) {
ToPool(node);
}
}
public void Dispose() {
ToPool(this);
}
public static int PoolSize() {
if (_nodePool == null) return 0;
return _nodePool.Count;
}
}
IAStarNode is an interface, so there is no lingering fields from there, and my ToPool function clears out the only 4 fields this class has. If I change the FromPool function to this, it all works:
public static ShippingRouteNode FromPool() {
return new ShippingRouteNode();
}
This makes me sure that somehow the objects coming from the pool are not perfectly fresh. I just can’t figure out why they would contain old data.
I’ve checked the entire solution for all instances of new ShippingRouteNode(), and the only time is in FromPool.
Does anyone have any idea why my pooling is causing the pathfinding to fail?