为什么Unity不为我缓存组件



我为GetComponent((创建了自己的包装器,这样我就可以在任何我想要的地方使用它,而不会担心性能问题。

为什么Unity一开始就不这么做?这么简单的把戏会有问题吗?

我的代码(打算用作基类而不是MonoBehavior(:

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];
}
}
  • 它增加了行为的内存开销,还为每个实例添加了至少一个堆分配
  • 如果组件在运行时被删除并可能重新添加,它就会失败
  • 直接将组件缓存到自己的变量中(例如Awake((中(仍然更具性能

当然,在您的许多用例中,这些点可能可以忽略不计,并且您肯定可以在您认为合适的地方使用它,但这并不是在所有情况下都是一个好主意,这就是为什么不应该将其用于一般实现的原因。

最新更新