Esempio n. 1
0
    private string GetTagFromEnum(PooledObjects tagEnum)
    {
        switch (tagEnum)
        {
        case PooledObjects.PlayerBullet:
            return("PlayerBullet");

        case PooledObjects.EnemyBullet:
            return("EnemyBullet");

        case PooledObjects.TrippleShot:
            return("TrippleShot");

        case PooledObjects.PowerUp:
            return("PowerUp");

        case PooledObjects.ExplosionParticleSystem:
            return("ExplosionParticle");

        case PooledObjects.Enemy:
            return("Enemy");
        }

        return("");
    }
    public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation)
    {
        if (!poolDictionary.ContainsKey(tag))
        // Adding a '!' then placing your line after counts as a 'If this is not true' statement.
        {
            Debug.LogWarning("Pool with tag" + tag + " doesn't exist!");
            return(null);
            // If the ObjectPool has no object with the tag it is being asked for, this will stop errors being caused as it would try to spawn something when it has nothing to spawn.
        }
        GameObject objectToSpawn = poolDictionary[tag].Dequeue();

        objectToSpawn.SetActive(true);
        objectToSpawn.transform.position = position;
        objectToSpawn.transform.rotation = rotation;

        PooledObjects pooledObj = objectToSpawn.GetComponent <PooledObjects>();

        if (pooledObj != null)
        {
            pooledObj.OnObjectSpawn();
        }

        poolDictionary[tag].Enqueue(objectToSpawn);
        return(objectToSpawn);
    }
Esempio n. 3
0
    public GameObject GetPooledObject(PooledObjects tagEnum)
    {
        for (int i = 0; i < pooledObjects.Count; i++)
        {
            if (!pooledObjects[i].activeInHierarchy && pooledObjects[i].CompareTag(GetTagFromEnum(tagEnum)))
            {
                return(pooledObjects[i]);
            }
        }

        foreach (ObjectPoolItem item in itemsToPool)
        {
            if (item.objectToPool.CompareTag(GetTagFromEnum(tagEnum)))
            {
                if (item.shouldExpand)
                {
                    GameObject obj = Instantiate(item.objectToPool);
                    obj.SetActive(false);
                    pooledObjects.Add(obj);
                    return(obj);
                }
            }
        }

        return(null);
    }
Esempio n. 4
0
    public static GameObject Spawn(GameObject prefab, Vector3 pos, Quaternion rot)
    {
        PooledObjects cache = null;

        // Find the cache for the specified prefab
        if (spawner)
        {
            for (int i = 0; i < spawner.caches.Length; i++)
            {
                if (spawner.caches[i].prefab == prefab)
                {
                    cache = spawner.caches[i];
                }
            }
        }

        // If there's no cache for this prefab type, just instantiate normally
        if (cache == null)
        {
            return(Instantiate(prefab, pos, rot) as GameObject);
        }

        // Find the next object in the cache
        GameObject obj = cache.GetNextObjectInCache();

        // Set the postion and rotation of the object
        obj.transform.position = pos;
        obj.transform.rotation = rot;

        // Set the object to be active
        obj.SetActive(true);
        spawner.activeCachedObjects[obj] = true;

        return(obj);
    }
Esempio n. 5
0
        private void AdjustPoolSizeToBounds()
        {
            // If there is an Adjusting operation in progress, skip and return.
            if (Interlocked.CompareExchange(ref AdjustPoolSizeIsInProgressCASFlag, 1, 0) == 0)
            {
                // If we reached this point, we've set the AdjustPoolSizeIsInProgressCASFlag to 1
                // (true) - using the above CAS function We can now safely adjust the pool size
                // without interferences

                // Adjusting...
                while (ObjectsInPoolCount < MinimumPoolSize)
                {
                    PooledObjects.Enqueue(CreatePooledObject());
                }

                while (ObjectsInPoolCount > MaximumPoolSize)
                {
                    T dequeuedObjectToDestroy;
                    if (PooledObjects.TryDequeue(out dequeuedObjectToDestroy))
                    {
                        // Diagnostics update
                        Diagnostics.IncrementPoolOverflowCount();

                        DestroyPooledObject(dequeuedObjectToDestroy);
                    }
                }

                // Finished adjusting, allowing additional callers to enter when needed
                AdjustPoolSizeIsInProgressCASFlag = 0;
            }
        }
    //! Get your thing
    public GameObject GetPooledObject(PooledObjects findType)
    {
        for (int i = 0; i < objectPoolList.Count; i++)
        {
            ObjectPool curPool = objectPoolList[i];
            if (curPool.poolType == findType)
            {
                for (int j = 0; j < curPool.pooledObjects.Count; j++)
                {
                    if (curPool.pooledObjects[j].activeInHierarchy == false)
                    {
                        return(curPool.pooledObjects[j]);
                    }
                }

                if (curPool.canExpand == false)
                {
                    return(null);
                }
                else
                {
                    GameObject obj = (GameObject)Instantiate(curPool.poolObj, Vector3.zero, Quaternion.identity);
                    curPool.pooledObjects.Add(obj);
                    return(obj);
                }
            }
        }

        Debug.LogError("Cannot find " + findType + " pool");
        return(null);
    }
Esempio n. 7
0
        /// <summary>
        ///   Get a monitored object from the pool.
        /// </summary>
        /// <returns></returns>
        public T GetObject()
        {
            T dequeuedObject = null;

            if (PooledObjects.TryDequeue(out dequeuedObject))
            {
                // Invokes AdjustPoolSize asynchronously
                ThreadPool.QueueUserWorkItem(new WaitCallback((o) => AdjustPoolSizeToBounds()));

                // Diagnostics update
                Diagnostics.IncrementPoolObjectHitCount();

                return(dequeuedObject);
            }
            else
            {
                // This should not happen normally, but could be happening when there is stress on
                // the pool No available objects in pool, create a new one and return it to the caller
                Debug.Print("Object pool failed to return a pooled object. pool is empty. consider increasing the number of minimum pooled objects.");

                // Diagnostics update
                Diagnostics.IncrementPoolObjectMissCount();

                return(CreatePooledObject());
            }
        }
Esempio n. 8
0
        /// Get a monitored object from the pool.
        public T GetObject()
        {
            T dequeuedObject = (PooledObjects.Count == 0) ? null : PooledObjects.Dequeue();

            if (dequeuedObject != null)
            {
                AdjustPoolSizeToBounds();

                // Diagnostics update
                Diagnostics.IncrementPoolObjectHitCount();

                return(dequeuedObject);
            }
            else
            {
                // This should not happen normally, but could be happening when there is stress on the pool
                // No available objects in pool, create a new one and return it to the caller
                //Debug.log("Object pool failed to return a pooled object. pool is empty. consider increasing the number of minimum pooled objects.");

                // Diagnostics update
                Diagnostics.IncrementPoolObjectMissCount();

                return(CreatePooledObject());
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Adds a new game object to the object pool from a specified index of the PoolObjects; returns new game object if needed.
        /// </summary>
        /// <param name="index">Index of PoolObjects to get game object from.</param>
        /// <param name="disable">True to disable new game object, false to not disable game object.</param>
        /// <returns></returns>
        public GameObject AddObjectFrom(int index, bool disable = false)
        {
            if (PoolObjects == null)
            {
                Debug.LogError("\"poolObject\" is null! Please make sure it's assigned in the Unity Editor.");
                return(null);
            }

            if (PoolObjects.Length < index)
            {
                Debug.LogError("The length of the PoolObjects variable is too short! Make sure you don't try to access something that is not there!");
                return(null);
            }

            //Create GameObject
            GameObject obj = (GameObject)Object.Instantiate(PoolObjects[index], poolHolder.transform);

            PooledObjects.Add(obj);

            //Set game object in-active if told to do so
            if (disable)
            {
                obj.SetActive(false);
            }

            return(obj);
        }
    public static GameObject Spawn(PooledObjects pooledObject, Transform parent)
    {
        var obj = _instance.SpawnFromPool(pooledObject, Vector3.zero, Quaternion.identity);

        obj.transform.SetParent(parent);
        obj.transform.position = Vector3.zero;
        return(obj);
    }
Esempio n. 11
0
    /// <summary>
    /// Adds a new object to the object pool, and returns it if needed.
    /// </summary>
    /// <returns>The newly added object.</returns>
    public virtual T AddObject()
    {
        T obj = new T();

        PooledObjects.Add(obj);

        return(obj);
    }
Esempio n. 12
0
    IEnumerator CreateObjects(PooledObjects objectType, int count)
    {
        for (int i = 0; i < count; ++i)
        {
            GameObject g = Instantiate(Resources.Load(resourceNames[(int)objectType]), Vector3.zero, Quaternion.identity, transform) as GameObject;
            g.SetActive(false);
            pool[(int)objectType].Add(g);
        }

        initializing[(int)objectType] = false;
        yield break;
    }
Esempio n. 13
0
    public static GameObject GetCachedObject(GameObject prefab)
    {
        PooledObjects cache = null;

        if (spawner)
        {
            for (int i = 0; i < spawner.caches.Length; i++)
            {
                if (spawner.caches[i].prefab == prefab)
                {
                    cache = spawner.caches[i];
                }
            }
        }

        return(cache.GetActiveObject());
    }
Esempio n. 14
0
        internal void ReturnObjectToPool(PooledObject objectToReturnToPool, bool reRegisterForFinalization)
        {
            T returnedObject = (T)objectToReturnToPool;

            // Diagnostics update
            if (reRegisterForFinalization)
            {
                Diagnostics.IncrementObjectRessurectionCount();
            }

            // Checking that the pool is not full
            if (ObjectsInPoolCount < MaximumPoolSize)
            {
                // Reset the object state (if implemented) before returning it to the pool. If
                // reseting the object have failed, destroy the object
                if (!returnedObject.ResetState())
                {
                    // Diagnostics update
                    Diagnostics.IncrementResetStateFailedCount();

                    DestroyPooledObject(returnedObject);
                    return;
                }

                // re-registering for finalization - in case of resurrection (called from Finalize method)
                if (reRegisterForFinalization)
                {
                    GC.ReRegisterForFinalize(returnedObject);
                }

                // Diagnostics update
                Diagnostics.IncrementReturnedToPoolCount();

                // Adding the object back to the pool
                PooledObjects.Enqueue(returnedObject);
            }
            else
            {
                // Diagnostics update
                Diagnostics.IncrementPoolOverflowCount();

                //The Pool's upper limit has exceeded, there is no need to add this object back into the pool and we can destroy it.
                DestroyPooledObject(returnedObject);
            }
        }
Esempio n. 15
0
    /// <summary>
    /// Function creates GameObject of specific objectType, if object doesn't exit in object pool, it gets instantiated.
    /// </summary>
    /// <param name="objectType"></param>
    /// <param name="position"></param>
    /// <param name="rotation"></param>
    /// <param name="activate"></param>
    /// <returns></returns>
    public GameObject InstantiateObject(PooledObjects objectType, Vector3 position, Quaternion rotation, bool activate = true)
    {
        // if pool is empty, instantiate
        if (pool[(int)objectType].Count == 0)
        {
            GameObject g = Instantiate(Resources.Load(resourceNames[(int)objectType]), Vector3.zero, Quaternion.identity, transform) as GameObject;
            pool[(int)objectType].Add(g);
        }

        // return first available object
        Transform obj = pool[(int)objectType][0].transform;

        obj.position = position;
        obj.rotation = rotation;
        pool[(int)objectType].RemoveAt(0);
        obj.gameObject.SetActive(activate);

        return(obj.gameObject);
    }
Esempio n. 16
0
        /// <summary>
        /// Adds a new game object to the object pool, and returns it if needed.
        /// </summary>
        /// <param name="disable">True to disable new game object, false to not disable game object.</param>
        /// <returns>The newly added game object.</returns>
        public GameObject AddRandomObject(bool disable = false)
        {
            if (PoolObjects == null)
            {
                Debug.LogError("\"poolObject\" is null! Please make sure it's assigned in the Unity Editor.");
                return(null);
            }

            //Create GameObject
            GameObject obj = (GameObject)Object.Instantiate(PoolObjects[Random.Range(0, PoolObjects.Length)], poolHolder.transform);

            PooledObjects.Add(obj);

            //Set game object in-active if told to do so
            if (disable)
            {
                obj.SetActive(false);
            }

            return(obj);
        }
    public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation)
    {
        if (!poolDictionary.ContainsKey(tag))
        // Adding a '!' then placing your line after counts as a 'If this is not true' statement.
        {
            Debug.LogWarning("Pool with tag" + tag + " doesn't exist!");
            return(null);
            // If the ObjectPool has no object with the tag it is being asked for, this will stop errors being caused as it would try to spawn something when it has nothing to spawn.
        }
        GameObject objectToSpawn = poolDictionary[tag].Dequeue();

        // Dequeues an object, because we are pulling this object to be spawned.

        objectToSpawn.SetActive(true);               // The dequeued object is set to become 'active'.
        objectToSpawn.transform.position = position; // Depends on inputs as to where it spawns.
        objectToSpawn.transform.rotation = rotation; // Depends on inputs as to how Euler angles affect it itself.

        PooledObjects pooledObj = objectToSpawn.GetComponent <PooledObjects>();

        // Gets alls the components of the object.
        if (pooledObj != null)         // Makes sure we are spawning 'something' and not 'nothing'.
        {
            pooledObj.OnObjectSpawn(); // Allows it to spawn.
        }

        if (pooledObj == null)
        {
            Debug.LogWarning("There are no more objects of this type!");
            // For some reason, this is firing off without any reason. I have absolutely no idea, and it would probably lead to multiple leak pool leaks if left unfixed...
            // ... but i honestly don't care enough and don't have time to go digging into this, because I have only one ObjectPool.
            // As it stands, nothing is *really* broken, despite it being inherently broken here for some reason.
            // Motto for the time being? 'If it isn't truly broken, don't mess with it'.
        }

        poolDictionary[tag].Enqueue(objectToSpawn);
        return(objectToSpawn);        // Returns a GameObject, the object to spawn.
    }
Esempio n. 18
0
        /// <summary>
        /// Get a monitored object from the pool.
        /// </summary>
        /// <returns></returns>
        public T GetObject()
        {
            T dequeuedObject = null;

            if (PooledObjects.Count > 0)
            {
                dequeuedObject = PooledObjects.First.Value;
                PooledObjects.RemoveFirst();
                // Invokes AdjustPoolSize asynchronously
                AdjustPoolSizeToBounds();
                // Diagnostics update
                Diagnostics.IncrementPoolObjectHitCount();
                return(dequeuedObject);
            }
            else
            {
                // This should not happen normally, but could be happening when there is stress on the pool
                // No available objects in pool, create a new one and return it to the caller
                System.Diagnostics.Debug.WriteLine("Object pool failed to return a pooled object. pool is empty. consider increasing the number of minimum pooled objects.");
                // Diagnostics update
                Diagnostics.IncrementPoolObjectMissCount();
                return(CreatePooledObject());
            }
        }
Esempio n. 19
0
        private void AdjustPoolSizeToBounds()
        {
            // If we reached this point, we've set the AdjustPoolSizeIsInProgressCASFlag to 1 (true) - using the above CAS function
            // We can now safely adjust the pool size without interferences

            // Adjusting...
            while (PooledObjects.Count < _MinimumPoolSize)
            {
                PooledObjects.Enqueue(CreatePooledObject());
            }

            while (PooledObjects.Count > _MaximumPoolSize)
            {
                T dequeuedObjectToDestroy = PooledObjects.Dequeue();

                if (dequeuedObjectToDestroy != null)
                {
                    // Diagnostics update
                    Diagnostics.IncrementPoolOverflowCount();

                    DestroyPooledObject(dequeuedObjectToDestroy);
                }
            }
        }
Esempio n. 20
0
 /// <summary>
 /// Function returns GameObject to object pool.
 /// </summary>
 /// <param name="objectType"></param>
 /// <param name="objectToReturn"></param>
 public void Free(PooledObjects objectType, GameObject objectToReturn)
 {
     Free(objectType, objectToReturn.transform);
 }
Esempio n. 21
0
 /// <summary>
 /// Function returns GameObject to object pool.
 /// </summary>
 /// <param name="objectType"></param>
 /// <param name="objectToReturn"></param>
 public void Free(PooledObjects objectType, Transform objectToReturn)
 {
     objectToReturn.gameObject.SetActive(false);
     pool[(int)objectType].Add(objectToReturn.gameObject);
 }
Esempio n. 22
0
 /// <summary>
 /// Deletes all objects that are currently in the object pool list.
 /// </summary>
 public virtual void DeleteAllObjects()
 {
     PooledObjects.Clear();
 }
Esempio n. 23
0
 public void Initialize(PooledObjects objectType, int size)
 {
     initializing[(int)objectType] = true;
     StartCoroutine(CreateObjects(objectType, size));
 }
Esempio n. 24
0
 /// <summary>
 /// Function creates GameObject of specific objectType, if object doesn't exit in object pool, it gets instantiated.
 /// </summary>
 /// <param name="objectType"></param>
 /// <param name="position"></param>
 /// <param name="activate"></param>
 /// <returns></returns>
 public GameObject InstantiateObject(PooledObjects objectType, Vector3 position, bool activate = true)
 {
     return(InstantiateObject(objectType, position, Quaternion.identity, activate));
 }
 public static T Spawn <T>(PooledObjects pooledObject, Transform parent)
 {
     return(Spawn(pooledObject, parent).GetComponent <T>());
 }
 public static GameObject Spawn(PooledObjects pooledObject)
 {
     return(_instance.SpawnFromPool(pooledObject, Vector3.zero, Quaternion.identity));
 }
 public static T Spawn <T>(PooledObjects pooledObject, Vector3 position, Quaternion rotation)
 {
     return(_instance.SpawnFromPool(pooledObject, position, rotation).GetComponent <T>());
 }
 public static GameObject Spawn(PooledObjects pooledObject, Vector3 position, Quaternion rotation)
 {
     return(_instance.SpawnFromPool(pooledObject, position, rotation));
 }
 private GameObject SpawnFromPool(PooledObjects pooledObject, Vector3 position, Quaternion rotation)
 {
     if (!_poolDictionary.ContainsKey(pooledObject))
     {
         Debug.Log($"Pool with type {pooledObject} doesn't exist.");
         return(default);