Orion31
Orion31

Reputation: 596

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.

Upvotes: 4

Views: 2511

Answers (2)

gaweph
gaweph

Reputation: 136

You are looking for TryGetComponent

    if (TryGetComponent(out MyComponent myComponent))
    {
        // do something
    }

Upvotes: 12

Nika Kasradze
Nika Kasradze

Reputation: 3019

how about:

MyComponent myComponent = gameObject.GetComponent<MyComponent>();
if (myComponent == null) return

// do something

Upvotes: 0

Related Questions