Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity - Get Component and Check for Null in One Line?

Is there a way to simplify the following block of code?

MyComponent myComponent = gameObject.GetComponent<MyComponent>();
if (myComponent != null)
{
    // do something
}

Something like

if (var myComponent = gameObject.GetComponent<MyComponent>() != null) {
    // do something
}

My motive for doing this is because I am raycasting a mouse press, and I want the type of the object that the user clicked on to affect what happens. For example, I would do something like

ComponentOne componentOne = gameObject.GetComponent<ComponentOne>();
if (componentOne != null)
{
    // do something
    return;
}

ComponentTwo componentTwo = gameObject.GetComponent<ComponentTwo>();
if (componentTwo != null)
{
    // do something
    return;
}

ComponentThree componentThree = gameObject.GetComponent<ComponentThree >();
if (componentThree != null)
{
    // do something
    return;
}

However, this is messy and unnecessarily lengthy.

like image 264
Orion31 Avatar asked Oct 26 '25 07:10

Orion31


1 Answers

You are looking for TryGetComponent

    if (TryGetComponent(out MyComponent myComponent))
    {
        // do something
    }
like image 131
gaweph Avatar answered Oct 29 '25 05:10

gaweph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!