placeholderfeatureplaceholdersliderplaceholderthumb

Unity's TryGetComponent Method

by Hunter Pankey

Starting in Unity 2019.2, GameObjects now have a TryGetComponent() method that attempts to get a component on the game object and return it (via an out parameter), as well as returning a boolean for whether the operation was successful. One should basically never use the old GameObject.GetComponent() method now that TryGetComponent() is available. (I’m sure a good use case could be coerced from some scenario, but for most cases, this new one’ll do much better.)

Basically, instead of doing:

Rigidbody rb = this.GetComponent<Rigidbody>();

if(rb != null)
{
// do whatever ole thing with the Rigidbody
}

This can be kinda cleaned up into the following:

if(this.TryGetComponent<Rigidbody>(out Rigidbody rb))
{
// do whatever you were gonna do with the Rigidbody using the rb variable
}

They both accomplish basically the same thing, but the second is a little more concise.

Note: There’s a similar pattern when raycasting with Physics.Raycast() and similar methods:

if(Physics.Raycast(position, direction, out RaycastHit hit, distance, layerMask))
{
// hit was successful, use hit variable here
}