hi,everyone ,i just watched the live archive about the object pooling,and when i wrote it myself and got this question,here is my code piece:
using UnityEngine;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MyObjectPool : MonoBehaviour {
public static MyObjectPool current;
public List<GameObject> poolObjects;
public Dictionary<string,List<GameObject>> diffPooledObjects;
private int poolAmount ;
void Awake(){
current = this;
}
void Start(){
poolAmount = 10;
diffPooledObjects = new Dictionary<string,List<GameObject>>();
CreatePoolObjects ();
}
void CreatePoolObjects(){
foreach(GameObject poolObj in poolObjects){
List<GameObject> tempList = new List<GameObject>();
for(int i = 0; i < poolAmount; i++){
GameObject tempObj = (GameObject)Instantiate(poolObj);
tempObj.SetActive(false);
tempList.Add(tempObj);
}
diffPooledObjects.Add (poolObj.name,tempList);
}
}
public GameObject GetPooledObject(string name){
List<GameObject> pooledObjects;
if(diffPooledObjects.TryGetValue(name,out pooledObjects)){
for(int i = 0; i < pooledObjects.Count; i++){
if(!pooledObjects[i].activeInHierarchy){
return pooledObjects[i];
}
}
GameObject tempObj = (GameObject)Instantiate(pooledObjects[0]);
tempObj.SetActive(false);
pooledObjects.Add(tempObj);
return tempObj;
}else{
return null;
}
}
}
im doing the infinite runner game llike the live archive said
1.i have three types of gameobject to be pooled:small ground,midium ground and large ground,
2.In Unity inspector,i put the references of these ground prefabs to the List “poolObjects”
3.The Dictionary<string,List> means that each List is a object pool,derminated by object name
4.In the CreatePoolObjects() ,i just intialize all the object pools,
5…In GetPooledObject(string name),i want to get object from different object pools by string
here is the exception:
NullReferenceException: Object reference not set to an instance of an object
MyObjectPool.GetPooledObject (System.String name) (at Assets/Scripts/ObjectPool/MyObjectPool.cs:31),
accur at " if(diffPooledObjects.TryGetValue(name,out pooledObjects)){"