ObjectPool for Class Instances using Built-In Array
Hi there,
I have super simple problem i'm struggling with.
Im trying to reuse custom MyClass instances, so i've built an Object pool for them. Basically, when a reference to an instance is no longer needed on stage, its moved into the pool.
To move the reference (pointer), i point it to an ObjectPool.myArray[i], and (if using a List as the on-stage collection type), i use MyList.RemoveAt to remove the list item from that List.
This works, as RemoveAt doesnt nullify the MyClass instance, only removes its pointer (which prior to that, is assigned into ObjectPool's myArray[i]).
That works, however i want to use built-in array for on-stage display, not a List.
QUESTION
How to remove pointer to an item from built-in Array, without nullifying the value?
All i know is possible with built-in arrays is this:
array[i] = null;
But that destroys the instance. I only want to (re)move the pointer.
Another approach i can think of is: assigning a copy of the built in array to the builtin array "with the item in question nullified" - did not test this yet, but if this works, it seems expensive and seems to defeat the purpose of using builtin array in the first place ( i like my fixed-size, indexed, speedy collection type) - but i could just use List.removeAt / List.Insert instead.. (not a fan)
Thoughts please
Answer by _watcher_ · May 04, 2017 at 11:44 AM
I've made some tests, and realized my own ignorance! Apparently what i wrote above is NOT correct.
Truth is:
Nullifying built-in array item's value doesn't destroy the instance, only removes the pointer.
Some examples you can run yourself:
using System.Collections.Generic;
using UnityEngine;
public class OneTimeSimpleTests : MonoBehaviour
{
public class MyClass
{
// gameobj reference
public GameObject gameObject;
// array of strings reference
public string[] strArray;
}
private MyClass[] classArr1;
private MyClass[] classArr2;
void Start () {
/// INIT
///
classArr1 = new MyClass[10];
classArr2 = new MyClass[10];
// fill in the arrays
for (int i = 0; i < 10; i++)
{
// class instances must be manually instantiated
classArr1[i] = new MyClass();
classArr2[i] = new MyClass();
classArr1[i].strArray = new string[2] { "five", "six" };
classArr2[i].strArray = new string[2] { "seven", "eight" };
}
// TESTS
//
MyClass inst = classArr1[0];
classArr1[0] = null;
Debug.Log(inst); // MyClass // HOHOOO!
classArr1[0] = classArr2[0];
classArr2[0] = null;
Debug.Log(classArr1[0]); // MyClass // HOHOOO!
classArr2[0].gameObject = gameObject;
classArr1[0].gameObject = classArr2[0].gameObject;
classArr2[0].gameObject = null;
Debug.Log(classArr1[0].gameObject); // GameObject // HOHOOO!
classArr2[0].gameObject = gameObject;
classArr1[0].gameObject = classArr2[0].gameObject;
DestroyImmediate(classArr2[0].gameObject);
Debug.Log(classArr1[0].gameObject); // null
}
}