Good example why you should cache components

This is a very good example why you actually should cache components as variables and call GetComponent only once.

If you call GetComponent OnEnable to add a listener to an Action and call GetComponent OnDisable to remove a listener it might not be the same component & Action and it would not result in the wanted behavior.

[Advanced]

I almost always use GetComponent on Awake.
But the same error can happen if you use a property you want to listen to for example. I had this error a few times to debug and had to make sure it’s always the same reference I call the Action from.

In most circumstances, at least on the same GameObject, GetComponent should yield the same result from anywhere, making it generally safe (and recommended) to cache.
On another GameObject, or an assigned target, for example, you don’t have that same guarantee, and caching the component can lead to an NRE

1 Like

Yes, the reference and cached variable (especially from another GameObject) can become null between adding a listener and trying to remove the listener. That’s why I make a null check. If it is null I do not have to worry about removing the listener anyway.
Simple example is quitting the app and objects with actions get destroyed before the listeners with cached variables are removed.

But you can’t rely on a getter like GetComponent or in form of a property to add and remove a listener from the same object. That’s why I suggest better cache the reference with the action before adding the listener and make a null check & remove the listener with the cached variable, because that’s the referenced action you care about.

Privacy & Terms