I’ve recently learned about the benefits of pooling game objects and recycling them over instantiating and destroying them. Unity has a nice tutorial for this but it dealt only with pooling just one object and I’d like a system that lets me pool multiple different objects. Can’t quite get it to work though. Here is the object pooling script I have so far:
public GameObject[] objects;
public int[] number;
public List<GameObject>[] pool;
void Start () {
instantiate();
}
void instantiate(){
GameObject temp;
pool = new List<GameObject>[objects.Length];
for(int count = 0; count < objects.Length; count++){
pool[count] = new List<GameObject>();
for(int num = 0; num < number[count]; num++){
temp = (GameObject)Instantiate(objects[count]);
temp.transform.parent = this.transform;
pool[count].Add(temp);
}
}
}
public GameObject activate(int id){
for(int count = 0; count < pool[id].Count; count++){
if(!pool[id][count].activeSelf){
pool[id][count].SetActive(true);
return pool[id][count];
}
}
return null;
}
I plug my bullet prefab into the first element in the list and then set how many of them I want instantiated. No problem. The only error I’m getting is from my shoot script:
public ObjectPooler pool;
private Transform myTransform;
private Transform cameraHeadTransform;
private Vector3 launchPosition = new Vector3();
public float fireRate = 0.2f;
public float nextFire = 0;
// Use this for initialization
void Start () {
myTransform = transform;
cameraHeadTransform = myTransform.FindChild("BulletSpawn");
}
void Update () {
if(Input.GetButton("Fire1") && Time.time > nextFire){
nextFire = Time.time + fireRate;
launchPosition = cameraHeadTransform.TransformPoint(0, 0, 0.2f);
GameObject current = pool.activate(0);
current.transform.position = launchPosition;
current.transform.rotation = Quaternion.Euler(cameraHeadTransform.eulerAngles.x + 90, myTransform.eulerAngles.y, 0);
}
}
Pressing the Fire1 button gives prompts:
“NullReferenceException: Object reference not set to an instance of an object” for line 33. Any ideas whats going on?