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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With