Trouble getting a game object from object pool in Unity

user3776884

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

Imapler

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);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Java - War Game - Getting an object from an array

From Dev

Trouble getting input for object array

From Dev

Having trouble getting access to the Object in JSON from url

From Dev

Having trouble getting access to the Object in JSON from url

From Dev

Unity - How do I apply an animation from one game object to another rigged game object?

From Dev

Trouble when build android game from unity

From Dev

Trouble getting properties and object structured correctly

From Dev

How to make game object transparent in unity

From Dev

Collision Detection for fast moving game object in Unity

From Dev

Unity - How to separate the children of a game object linearly?

From Dev

Unity is possible to add a Game Object in hierarchy but not instantiate it?

From Dev

Unity3d - How to make method calling from another class that belongs to another game object efficiently

From Dev

How to have a Game Object remove itself from a list? (Unity3d)

From Dev

Having a trouble dealing with the object returned from NSUserDefaults

From Dev

Trouble creating object from Json using Knockout

From Dev

Trouble returning an object from a class I created

From Dev

Keep getting [object] [Object] from variable

From Dev

Keep getting [object, Object] from array for $.each

From Dev

Getting an element from vector<object*> *object

From Dev

Getting particular object from nested complex object

From Dev

connection object from hikaricp connection pool

From Dev

connection object from hikaricp connection pool

From Dev

Monitor a multiprocessing.pool.Pool object from an async function

From Dev

How to move a game object in the forwrard direction of an other game object Unity3D

From Dev

Trouble getting size of an array in a js object inside controller

From Dev

Getting a File object from FileInputStream

From Dev

Getting A Selected Object from GridView

From Dev

Getting value from a collection object

From Dev

Getting settings object from the buildscript

Related Related

  1. 1

    Java - War Game - Getting an object from an array

  2. 2

    Trouble getting input for object array

  3. 3

    Having trouble getting access to the Object in JSON from url

  4. 4

    Having trouble getting access to the Object in JSON from url

  5. 5

    Unity - How do I apply an animation from one game object to another rigged game object?

  6. 6

    Trouble when build android game from unity

  7. 7

    Trouble getting properties and object structured correctly

  8. 8

    How to make game object transparent in unity

  9. 9

    Collision Detection for fast moving game object in Unity

  10. 10

    Unity - How to separate the children of a game object linearly?

  11. 11

    Unity is possible to add a Game Object in hierarchy but not instantiate it?

  12. 12

    Unity3d - How to make method calling from another class that belongs to another game object efficiently

  13. 13

    How to have a Game Object remove itself from a list? (Unity3d)

  14. 14

    Having a trouble dealing with the object returned from NSUserDefaults

  15. 15

    Trouble creating object from Json using Knockout

  16. 16

    Trouble returning an object from a class I created

  17. 17

    Keep getting [object] [Object] from variable

  18. 18

    Keep getting [object, Object] from array for $.each

  19. 19

    Getting an element from vector<object*> *object

  20. 20

    Getting particular object from nested complex object

  21. 21

    connection object from hikaricp connection pool

  22. 22

    connection object from hikaricp connection pool

  23. 23

    Monitor a multiprocessing.pool.Pool object from an async function

  24. 24

    How to move a game object in the forwrard direction of an other game object Unity3D

  25. 25

    Trouble getting size of an array in a js object inside controller

  26. 26

    Getting a File object from FileInputStream

  27. 27

    Getting A Selected Object from GridView

  28. 28

    Getting value from a collection object

  29. 29

    Getting settings object from the buildscript

HotTag

Archive