I've created my own wrapper for GetComponent() so that I could use it wherever I wanted without perfomance concerns.
Why does not Unity do that in the first place? Could there be problems with such simple trick?
My code (intended to be used as a base class instead of MonoBehaviour):
public abstract class MonoBase : MonoBehaviour
{
private readonly Dictionary<Type, Component> _components = new();
public new T GetComponent<T>() where T : Component
{
var type = typeof(T);
if (!_components.ContainsKey(type))
{
var component = gameObject.GetComponent<T>();
if (component != null)
_components.Add(type, component);
else
_components.Add(type, gameObject.AddComponent<T>());
}
return (T)_components[type];
}
}
CodePudding user response:
- It adds to the memory overhead of your behaviour and also adds at least one heap allocation for each of its instances.
- It fails if components get removed and maybe re-added at runtime.
- Directly caching the component e.g. in Awake() into its own variable is still more performant.
Of course these points may be negligible in many of your use-cases, and you can surely use it where you see fit, but it is not a good idea in every situation, which is why it should not be put into the general implementation.