- Home /
Question by
garrdev · Aug 21, 2017 at 02:24 AM ·
nullreferenceexceptionparentingparent-childobject poolparent transform
Instantiating child as parent not working : Object Pooling
I am making an endless runner game, and I am trying to use Object Pooling. When I try to set the transform of the child to the transform of the parent, it gives me an error:
NullReferenceException: Object reference not set to an instance of an object(wrapper stelemref) object:stelemref (object,intptr,object) ObjectPool.Start () (at Assets/Scripts/LevelScripts/ ObjectPool.cs:19)
Here is the code. Any answers are good! Thank You!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour {
private GameObject[][] objects = null;
public GameObject[] objectsToInstantiate1;
public GameObject[] objectsToInstantiate2;
public GameObject[] objectsToInstantiate3;
public GameObject[] objectsToInstantiate4;
public GameObject[] objectsToInstantiate5;
// Use this for initialization
void Start () {
objects = new GameObject[5][];
for (int i = 0; i < objectsToInstantiate1.Length; i++) {
objects [1] [i] = Instantiate (objectsToInstantiate1[i]) as GameObject;
objects [1] [i].transform.parent = gameObject.transform;
objects [1] [i].SetActive (false);
}
for (int j = 0; j < objectsToInstantiate2.Length; j++) {
objects [2] [j] = Instantiate (objectsToInstantiate2[j]) as GameObject;
objects [2] [j].transform.parent = gameObject.transform;
objects [2] [j].SetActive (false);
}
for (int k = 0; k < objectsToInstantiate3.Length; k++) {
objects [3] [k] = Instantiate (objectsToInstantiate3[k]) as GameObject;
objects [3] [k].transform.parent = gameObject.transform;
objects [3] [k].SetActive (false);
}
for (int l = 0; l < objectsToInstantiate4.Length; l++) {
objects [4] [l] = Instantiate (objectsToInstantiate4[l]) as GameObject;
objects [4] [l].transform.parent = gameObject.transform;
objects [4] [l].SetActive (false);
}
for (int m = 0; m < objectsToInstantiate5.Length; m++) {
objects [5] [m] = Instantiate (objectsToInstantiate5[m]) as GameObject;
objects [5] [m].transform.parent = gameObject.transform;
objects [5] [m].SetActive (false);
}
}
// Update is called once per frame
void Update () {
}
}
Comment
Best Answer
Answer by Nomenokes · Aug 21, 2017 at 04:04 AM
You need to set each GameObject[] as well. Right now the GameObject[][] is a new GameObject[][] of length 5, but each GameObject[] within that is still null.
for(int i=0;i<objects.Length;++){
objects[i]=new GameObject[5];
}
or if each "objectstoinstantiate" is a different length:
objects[0]=new GameObject[objectsToInstantiate1.Length];
objects[1]=new GameObject[objectsToInstantiate2.Length];
...