Hey all, I’m having an issue figuring out how to convert a generic Component into my desired component class.
Essentially I’ve created a pooling system that takes in a Type and a Component. I’ll add the relevant code below.
The issue I’m having is accessing the component once I’ve pulled it out of the pool.
private Dictionary<Type, List<Component>> _pooledObjects = new Dictionary<Type, List<Component>>();
public void PoolObject(Type componentType,Component component, bool add = true)
{
if (add)
{
if (_pooledObjects.ContainsKey(componentType))
{
_pooledObjects[componentType].Add(component);
return;
}
_pooledObjects.Add(componentType,new List<Component>{component});
return;
}
_pooledObjects[componentType].Remove(component);
}
Requesting from the Pool
public Component RequestComponentFromPool(Type componentType)
{
if (_pooledObjects[componentType][0] != null)
{
return _pooledObjects[componentType][0];
}
return null; // TODO
}
In this case, I’m wanting to reuse TextPopup’s from the pool and adjust the text accordingly. I guess my question is how do I convert from Unity’s generic Component into the desired one. While I could just access the GameObject from the returned component and use GetComponent I’m just sure there must be a way to access it without.
public class Utility : MonoBehaviour
{
public static void GenerateWorldText(string text,GameObject obj, float speed,float duration)
{
var textobj = Managers.PoolManager.
PoolManager.Instance.RequestComponentFromPool(typeof(TextPopup));
}
}