Generic use of Components through typeof(Component) | Convert from Unity's generic Component into a desired one
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));
}
}
Comment
Best Answer
Answer by Hellium · Apr 11, 2021 at 05:38 PM
private Dictionary<Type, List<Component>> _pooledObjects = new Dictionary<Type, List<Component>>();
public void PoolObject<T>(T component, bool add = true)
where T : Component
{
Type componentType = typeof(T);
if (!_pooledObjects.ContainsKey(componentType))
{
_pooledObjects.Add(componentType, new List<Component>());
}
if(add)
{
_pooledObjects[componentType].Add(component);
}
else
{
_pooledObjects[componentType].Remove(component);
}
}
public T RequestComponentFromPool<T>()
where T : Component
{
Type componentType = typeof(T);
if (_pooledObjects.ContainsKey(componentType) && _pooledObjects[componentType].Count > 0)
{
return _pooledObjects[componentType][0] as T;
}
return null;
}
PoolObject(GetComponent<Collider>());
Collider collider = RequestComponentFromPool<Collider>();
Debug.Log(collider);