Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Unity, if a component is found in an IF condition, use it immediately

I've seen a shorthand of "if a component was found in the IF condition, use it"

so instead of this

SomeScript script = gameObject.GetComponent<SomeScript>();

if (script != null) {
  script.DoSomething();
}

I saw some kind of shorthand like this

if (SomeScript script = gameObject.GetComponent<SomeScript>()) {
  script.DoSomething();
}

Anyone know what I mean? Sorry for not knowing the terminology

like image 797
Richard Muthwill Avatar asked Nov 17 '25 02:11

Richard Muthwill


1 Answers

You are most likely looking for the (recently added, I think starting from 2019.2 and up) TryGetComponent.

From the unity docs:

Gets the component of the specified type, if it exists.

TryGetComponent will attempt to retrieve the component of the given type. The notable difference compared to GameObject.GetComponent is that this method does not allocate in the Editor when the requested component does not exist.

using UnityEngine;

public class TryGetComponentExample : MonoBehaviour
{
    void Start()
    {
        if (TryGetComponent(out HingeJoint hinge))
        {
            hinge.useSpring = false;
        }
    }
}

Or using your example

if (TryGetComponent(out SomeScript script)) 
{
  script.DoSomething();
}

If the component gets found using TryGetComponent the reference to the found component will be stored in the out parameter, that you can then use inside the if block.

If no matching component is found it goes to the else section.

like image 101
Remy Avatar answered Nov 18 '25 14:11

Remy