Hello everyone, so I’m trying to create a Object Pooling script that does not use GetComponent.
Here are the reasons why I use GetComponent:
The Script
private Dictionary<string, Queue<GameObject>> poolDictionary;
// Set object to parent this organizer on hierarchy
[SerializeField]
private Transform pooledObjectsTransform = null;
// Objects
[System.Serializable]
public class Pool
{
public string tag;
[AssetsOnly]
public GameObject prefab;
public int size;
}
[SerializeField]
private List<Pool> pools = null;
/// <summary>
/// Spawn Prefab with Tag at new Position and new Rotation.
/// </summary>
/// <param name="Tag"></param>
/// <param name="Position"></param>
/// <param name="Rotation"></param>
/// <returns></returns>
public GameObject SpawnFromPool(string Tag, Vector3 Position, Quaternion Rotation)
{
if (!poolDictionary.ContainsKey(Tag))
{
Debug.LogWarning("Pool with name" + Tag + " doesn't exist.");
return null;
}
GameObject objectToSpawn = poolDictionary[Tag].Dequeue();
objectToSpawn.SetActive(true);
objectToSpawn.transform.position = Position;
objectToSpawn.transform.rotation = Rotation;
// Call object on spawn method
IPooledObjects[] _pooledObj = objectToSpawn.GetComponents<IPooledObjects>();
if (_pooledObj != null)
{
foreach (IPooledObjects pooledObj in _pooledObj)
{
pooledObj.OnObjectSpawn();
}
}
poolDictionary[Tag].Enqueue(objectToSpawn);
return objectToSpawn;
}
So everytime I spawn an object it will call a GetComponent to get the interface IPooledObjects and in some cases everytime I pool an object I’ll try to get a script from it to modify some values, the idea is to store this core scripts somewhere so I only call the GetComponent once, not everytime I spawn the object.
I thought of Generic Types, something around creating a class that can store any script as a type, but I still can’t wrap my head around it.
Thanks for your time!