Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Assertions;
- public class PrefabPool : MonoBehaviour
- {
- public MonoBehaviour prefab;
- public int objectCount = 64;
- public bool preallocate = true;
- public bool sceneObject = false;
- Stack< GameObject > inactiveObjects = new Stack< GameObject >();
- List< GameObject > activeObjects = new List< GameObject >();
- bool allocated = false;
- void Awake ()
- {
- if ( !allocated )
- Allocate();
- }
- public void Allocate ()
- {
- if ( sceneObject )
- {
- prefab.gameObject.SetActive( false );
- prefab.transform.SetParent( transform );
- }
- if ( !preallocate )
- {
- allocated = true;
- return;
- }
- for ( int i = 0; i <= objectCount; i++ )
- {
- if ( i == 0 && sceneObject )
- continue;
- GameObject obj = Instantiate( prefab.gameObject ) as GameObject;
- obj.SetActive( false );
- obj.transform.SetParent( transform );
- inactiveObjects.Push( obj );
- }
- allocated = true;
- }
- public T Spawn< T > () where T : MonoBehaviour
- {
- if ( !preallocate )
- {
- GameObject obj;
- if ( inactiveObjects.Count > 0 )
- {
- obj = inactiveObjects.Pop();
- obj.SetActive( true );
- activeObjects.Add( obj );
- return obj.GetComponent< T >() as T;
- }
- obj = Instantiate( prefab.gameObject, transform ) as GameObject;
- obj.SetActive( true );
- activeObjects.Add( obj );
- T result = obj.GetComponent< T >() as T;
- Assert.IsTrue( result != null, "Did not find " + typeof( T ) + " component on spawned object!" );
- return result;
- }
- if ( !allocated )
- Allocate();
- try
- {
- GameObject obj = inactiveObjects.Pop();
- obj.SetActive( true );
- activeObjects.Add( obj );
- return obj.GetComponent< T >() as T;
- }
- catch
- {
- Debug.LogError( name + ": RAN OUT OF OBJECTS", this );
- return null;
- }
- }
- public T Despawn< T > ( T obj ) where T : MonoBehaviour
- {
- Despawn( obj.gameObject );
- return obj;
- }
- public GameObject Despawn ( GameObject obj )
- {
- obj.SetActive( false );
- obj.transform.SetParent( transform );
- inactiveObjects.Push( obj );
- activeObjects.Remove( obj );
- return obj;
- }
- public void DespawnAll ()
- {
- int numActiveObjects = activeObjects.Count - 1;
- for ( int i = numActiveObjects; i >= 0; i-- )
- {
- activeObjects[ i ].SetActive( false );
- activeObjects[ i ].transform.SetParent( transform );
- inactiveObjects.Push( activeObjects[ i ] );
- }
- activeObjects.Clear();
- }
- public List< T > GetAll< T > () where T : MonoBehaviour
- {
- List< T > result = new List< T >();
- foreach ( GameObject obj in activeObjects )
- result.Add( obj.GetComponent< T >() );
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement