MonoGame.Extended icon indicating copy to clipboard operation
MonoGame.Extended copied to clipboard

[ObjectPool] not resetting _freeItems causes null reference

Open Elthial opened this issue 7 years ago • 0 comments

The ObjectPool does not reset T poolable when pulling it from the _freeitems deque.

This is a problem when you have an ObjectPool that calls Return on all of its items before having New called. This results in _tailNode being null because T CreateObject() is not called and there is no similar method to configure poolable from _freeitems deque.

Use(T item) is then called:

     private void Use(T item)
        {
            item.Initialize(_returnToPoolDelegate);
            item.NextNode = null;
            if (item != _tailNode)
            {
                item.PreviousNode = _tailNode;
                _tailNode.NextNode = item;
                _tailNode = item;
            }

            ItemUsed?.Invoke(item);
        }

item is a poolable component but _tailNode is null.

This passes the if (item != _tailNode) check and then promptly throws null reference exception on _tailNode.NextNode = item; because _tailNode is null.

I've resolved the issue for myself by just copying CreateObject() minus the TotalCount++ as a Reset method and adding to the if (!_freeItems.RemoveFromFront(out poolable)) as an else statement although that's quite the lazy fix.

if (!_freeItems.RemoveFromFront(out poolable))
            {
              \\\\\\\\etc etc
            }
            else
            {
                poolable = ResetObject();
            }

Elthial avatar Feb 11 '18 09:02 Elthial