Search code examples
c#unity-game-engineunityscriptobject-pooling

Trouble getting a game object from object pool in Unity


I was having trouble converting an object pool script from UnityScript to C#, which I got a lot of good help with here. Now I'm having an issue trying to actually get a game object from the pool. I have three scripts all interacting with one another, so I'm not quite sure where it's going wrong. Here are the two scripts for the object pool, which I believe are all squared away and they're not giving any errors:

public class EasyObjectPool : MonoBehaviour {
    [System.Serializable]
    public class PoolInfo{
        [SerializeField]
        public string poolName;
        public GameObject prefab;
        public int poolSize;
        public bool canGrowPoolSize = true;

}

[System.Serializable]
public class Pool{

    public List<PoolObject> list = new List<PoolObject>();
    public bool  canGrowPoolSize;

    public void  Add (PoolObject poolObject){
        list.Add(poolObject);
    }

    public int Count (){
        return list.Count;
    }


    public PoolObject ObjectAt ( int index  ){

        PoolObject result = null;
        if(index < list.Count) {
            result = list[index];
        }

        return result;

    }
}
static public EasyObjectPool instance ;

[SerializeField]
PoolInfo[] poolInfo = null;

private Dictionary<string, Pool> poolDictionary  = new Dictionary<string, Pool>();


void Start () {

    instance = this;

    CheckForDuplicatePoolNames();

    CreatePools();

}

private void CheckForDuplicatePoolNames() {

    for (int index = 0; index < poolInfo.Length; index++) {
        string poolName= poolInfo[index].poolName;
        if(poolName.Length == 0) {
            Debug.LogError(string.Format("Pool {0} does not have a name!",index));
        }
        for (int internalIndex = index + 1; internalIndex < poolInfo.Length; internalIndex++) {
            if(poolName == poolInfo[internalIndex].poolName) {
                Debug.LogError(string.Format("Pool {0} & {1} have the same name. Assign different names.", index, internalIndex));
            }
        }
    }
}

private void CreatePools() {

    foreach(PoolInfo currentPoolInfo in poolInfo){

        Pool pool = new Pool();
        pool.canGrowPoolSize = currentPoolInfo.canGrowPoolSize;

        for(int index = 0; index < currentPoolInfo.poolSize; index++) {
            //instantiate
            GameObject go = Instantiate(currentPoolInfo.prefab) as GameObject;
            PoolObject poolObject = go.GetComponent<PoolObject>();
            if(poolObject == null) {
                Debug.LogError("Prefab must have PoolObject script attached!: " + currentPoolInfo.poolName);
            } else {
                //set state
                poolObject.ReturnToPool();
                //add to pool
                pool.Add(poolObject);
            }
        }

        Debug.Log("Adding pool for: " + currentPoolInfo.poolName);
        poolDictionary[currentPoolInfo.poolName] = pool;

    }
}

public PoolObject GetObjectFromPool ( string poolName  ){
    PoolObject poolObject = null;

    if(poolDictionary.ContainsKey(poolName)) {
        Pool pool = poolDictionary[poolName];

        //get the available object
        for (int index = 0; index < pool.Count(); index++) {
            PoolObject currentObject = pool.ObjectAt(index);

            if(currentObject.AvailableForReuse()) {
                //found an available object in pool
                poolObject = currentObject;
                break;
            }
        }


        if(poolObject == null) {
            if(pool.canGrowPoolSize) {
                Debug.Log("Increasing pool size by 1: " + poolName);

                foreach (PoolInfo currentPoolInfo in poolInfo) {    

                    if(poolName == currentPoolInfo.poolName) {

                        GameObject go = Instantiate(currentPoolInfo.prefab) as GameObject;
                        poolObject = go.GetComponent<PoolObject>();
                        //set state
                        poolObject.ReturnToPool();
                        //add to pool
                        pool.Add(poolObject);

                        break;

                    }
                }
            } else {
                Debug.LogWarning("No object available in pool. Consider setting canGrowPoolSize to true.: " + poolName);
            }
        }

    } else {
        Debug.LogError("Invalid pool name specified: " + poolName);
    }

    return poolObject;
}

}

And:

public class PoolObject : MonoBehaviour {

[HideInInspector]
public bool availableForReuse = true;


void Activate () {

    availableForReuse = false;
    gameObject.SetActive(true);

}


public void ReturnToPool () {

    gameObject.SetActive(false);
    availableForReuse = true;


}

public bool AvailableForReuse () {
    //true when isAvailableForReuse & inactive in hierarchy

    return availableForReuse && (gameObject.activeInHierarchy == false);



}
}

The original UnityScript said to retrieve an object from the pool with this statement:

var poolObject : PoolObject = EasyObjectPool.instance.GetObjectFromPool(poolName);

This is how I tried to do that in my shooting script with it trying to fire a bullet prefab from the pool:

public class ShootScript : MonoBehaviour {

public PoolObject poolObject;

private Transform myTransform;

private Transform cameraTransform;

private Vector3 launchPosition = new Vector3();

public float fireRate = 0.2f;

public float nextFire = 0;

// Use this for initialization
void Start () {

    myTransform = transform;

    cameraTransform = myTransform.FindChild("BulletSpawn");

}


void Update () {

    poolObject = EasyObjectPool.instance.GetObjectFromPool<poolName>();

    if(Input.GetButton("Fire1") && Time.time > nextFire){

        nextFire = Time.time + fireRate;

        launchPosition = cameraTransform.TransformPoint(0, 0, 0.2f);

        poolObject.Activate();

        poolObject.transform.position = launchPosition;
        poolObject.transform.rotation = Quaternion.Euler(cameraTransform.eulerAngles.x + 90, myTransform.eulerAngles.y, 0);

    }

}
}

My shoot script is giving me two errors:

1. The type or namespace name 'poolName' could not be found. Are you missing a using directive or an assembly reference?

For the line:

poolObject = EasyObjectPool.instance.GetObjectFromPool<poolName>();

2. 'PoolObject.Activate()' is inaccessible due to its protection level

For the line:

poolObject.Activate();

Did I mis-translate the UnityScript or am I missing something else? Any input is greatly appreciated


Solution

  • The thing you write within <> should be a class name like PoolObject if the function is generic, which it is not. So to solve this you simply need to change

    poolObject = EasyObjectPool.instance.GetObjectFromPool<poolName>();
    

    to

    string poolName = "thePoolNameYouWant";
    poolObject = EasyObjectPool.instance.GetObjectFromPool(poolName);
    

    Function are private by default so to solve the "inaccessible due to its protection level" error you need to make the function public by changing this

    void Activate () {
        availableForReuse = false;
        gameObject.SetActive(true);
    }
    

    to this

    public void Activate () {
        availableForReuse = false;
        gameObject.SetActive(true);
    }