Exemple #1
0
    /// <summary>
    /// Spawns an object from the desired object pool.
    /// </summary>
    /// <param name="pooledObject"></param>
    /// <returns></returns>
    public static GameObject SpawnObject(PoolableObject pooledObject)
    {
        //If the static instance is null don't do anything and pop an error
        if (instance == null)
        {
            Debug.LogError("No Instance of ObjectPool exists");
            return(null);
        }

        //Ensure the key exists first
        if (instance.objectPool.ContainsKey(pooledObject))
        {
            if (instance.objectPool[pooledObject].Count < 1)
            {
                //If the queue was empty, but paddding was enabled, go ahead and add an additional entry
                if (instance.enablePadding)
                {
                    //Instansiate at scene origin
                    instance.AddEntry(pooledObject);
                }
                else
                {
                    Debug.LogError($"Queue empty for {pooledObject.poolableName}. Consider increasing pool size");
                    return(null);
                }
            }
            //Dequeue an object
            instance.objCache = instance.objectPool[pooledObject].Dequeue();
            //Enable/activate the object
            instance.objCache.SetActive(true);
            return(instance.objCache);
        }
        else
        {
            //If there wasn't a valid entry and unknown entry handling has been enabled, make an entry
            if (instance.unknownEntryHandling)
            {
                instance.objectPool.Add(pooledObject, new Queue <GameObject>());

                //For the number specified in the poolable object, instansiate the applicable prefab
                for (int i = 0; i < pooledObject.pooledAmount; i++)
                {
                    instance.AddEntry(pooledObject);
                }
                instance.objCache = instance.objectPool[pooledObject].Dequeue();
                instance.objCache.SetActive(true);
                return(instance.objCache);
            }
            //If there wasn't a valid entry and unknown entry handling has been disabled, just pop an error
            else
            {
                Debug.LogError($"No entry exists for '{pooledObject.poolableName}' in the object pool");
                return(null);
            }
        }
    }