GetComponent versus component.gameObject

If I don’t want to store both references in a script, which way round has less cost - storing the GameObject and looking for its main script with [game object].GetComponent when I need it, or storing the reference to the component and looking for the parent object with [component].gameObject when I need the object? I need to refer to each about an equal number of times.

.gameObject is instant (as is .transform, btw), while .GetComponent must search through all components of that object.

1 Like

Thank you! :slight_smile:

Oh and one more thing, if I only store the component reference, and then something in the game destroys the gameobject, does the reference to the component simply become a testable null?

Depends on the variable’s type that you use to store the reference.
If it’s an interface type or System.Object, you’ll be testing for ‘null’ only. A null-check would return false, as the C# object still exists in memory due to the reference you’re holding somewhere else.

If the variable’s type is UnityEngine.Object or anything more specialized down the hierarchy, you’d benefit from Unity’s customized null-check.

1 Like

Thanks :slight_smile: