Richard Muthwill
Richard Muthwill

Reputation: 336

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

Upvotes: 4

Views: 7070

Answers (3)

MatteKarla
MatteKarla

Reputation: 2737

If you want to run the method multiple times, then it's better to do it in two calls, first cache it in awake

 private someScript script;
 void Awake()
 {
     someScript = GetComponent<SomeScript>();
 }

And then when you use it in for example Update:

void Update()
{
     if(someScript)
     {
         // Do something with someScript
     }
     // or:
     someScript?.DoSomething();
 }

It's highly recommended that you annotate your script with the RequireComponent attribute:

[RequireComponent(typeof(SomeScript))]
public class MyScriptThatRequiresSomeScript : MonoBehaviour

Then the component is automatically added when you add your script to a game object

Upvotes: 0

Jeff
Jeff

Reputation: 860

The true one liner...

gameObject.GetComponent<SomeScript>()?.DoSomething();

Upvotes: 4

Remy
Remy

Reputation: 5173

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.

Upvotes: 7

Related Questions