3

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

user3776884
  • 85
  • 2
  • 7

2 Answers2

1

I think your object pool is incorrectly programmed. When you have a method like CheckForDuplicatePoolNames() ask yourself if you need a different collection like dictionary.

Keep it simple. I recently implemented one and I have tested. It works pretty well.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[System.Serializable]
public class PoolObject{
    public GameObject prefab;
    public int startNum;
    public int allocateNum;
    public Transform anchor;
}

public class ObjectPool<T> : MonoBehaviour where T:Component{
    public PoolObject[] poolObjects;
    public bool ______________;
    public Dictionary<string,Queue<T>> pool = new Dictionary<string, Queue<T>> ();
    public Dictionary<string, List<T>> spawned = new Dictionary<string, List<T>> ();
    public Transform anchor;


    public void Init(){
        InitPool ();
        StartAllocate ();
    }


    public T Spawn(string type){
        if (pool [type].Count == 0) {
            int i = FindPrefabPosition(type);
            if(poolObjects[i].allocateNum == 0)
                return null;
            Allocate(poolObjects[i], poolObjects[i].allocateNum);
        }
        T t = pool [type].Dequeue ();
        spawned[type].Add (t);
        t.gameObject.SetActive (true);
        return t;
    }


    public void Recycle(T t){
        if (spawned [t.name].Remove (t)) {
            pool[t.name].Enqueue(t);
            t.gameObject.SetActive(false);
        }
    }


    private void Allocate(PoolObject po, int number){
        for (int i=0; i<number; i++) {
            GameObject go = Instantiate (po.prefab) as GameObject;
            go.name = po.prefab.name;
            go.transform.parent = po.anchor != null? po.anchor : anchor;
            T t = go.GetComponent<T>();
            pool[t.name].Enqueue(t);
            t.gameObject.SetActive(false);  
        }
    }

    private int FindPrefabPosition(string type){
        int position = 0;
        while (poolObjects[position].prefab.name != type) {
            position++;     
        }
        return position;
    }

    void InitPool(){
        if(anchor == null)
            anchor = new GameObject("AnchorPool").transform;
        for (int i =0; i<poolObjects.Length; i++) {
            T t = poolObjects[i].prefab.GetComponent<T>();  
            t.name = poolObjects[i].prefab.name;
            pool[t.name] = new Queue<T>();
            spawned[t.name] = new List<T>();
        }
    }

    void StartAllocate(){
        for (int i=0; i<poolObjects.Length; i++) {
                Allocate(poolObjects[i], poolObjects[i].startNum );
        }
    }
}

Example:

public class CoinsPool : ObjectPool<CoinScript>{}

In the unity inspector configure the coin prefab, the startNum and the allocateNum.

Somewhere:

void Awake(){
  coinsPool = GetComponent<CoinsPool>();
  coinsPool.Init();
}

CoinScript cs = coinsPool.Spawn("Coin"); //Coin is the name of the coin prefab.

Later

coinsPool.Recycle(cs);
Roger Garzon Nieto
  • 6,554
  • 2
  • 28
  • 24
0

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);
}
Imapler
  • 1,401
  • 12
  • 26
  • Thanks for your help. Changing the poolObject line gave me some more errors: – user3776884 Jun 27 '14 at 17:20
  • The name `poolName' does not exist in the current context – user3776884 Jun 27 '14 at 17:21
  • The best overloaded method match for `EasyObjectPool.GetObjectFromPool(string)' has some invalid arguments – user3776884 Jun 27 '14 at 17:21
  • Argument `#1' cannot convert `object' expression to type `string' – user3776884 Jun 27 '14 at 17:21
  • poolName should be a string variable with the pool name you want. i have updated the answer, i believe all three errors are caused by this. All of these errors are very common to beginners and you should find a lot of information by just googleing the error message. – Imapler Jun 29 '14 at 10:31