Out parameter for GetComponent() and friends

It would be useful for, say, raycasting.

// Current method:
if (Physics.Raycast(ray, out RaycastHit hit, 1f))
{
    Player player = hit.transform.GetComponent<Player>();

    if (player)
    {
        // ...
    }
}

// Or, using pattern matching:
if (Physics.Raycast(ray, out RaycastHit hit, 1f))
{
    if (hit.transform.GetComponent<Player>() is Player player)
    {
        // ...
    }
}

// Proposed, a more elegant alternative to pattern matching:
if (Physics.Raycast(ray, out RaycastHit hit, 1f))
{
    if (hit.transform.GetComponent(out Player player))
    {
        // ...
    }
}

// Like most such things, this can be easily extracted into an extension method, but would be nice to have officially:
public bool GetComponent<T>(this Component component, out T t)
{
    T foundComponent = component.GetComponent<T>();

    t = foundComponent;

    return foundComponent; // This should work, since you can do `if (component)`. If not, cast?
}

there is: Unity - Scripting API: Component.TryGetComponent

1 Like

Huh. Well, thank you. It’s refreshing to come to the forum and not get ignored.

Alright, two issues with this:
1 - It was introduced in 2019.2. I’m stuck with 2019.1 for now.
2 - This is only available for GetComponent(), but I need it for GetComponentInParent() too.
Back to extension methods it is.

Great. With extension methods, you can’t use interfaces for that. Good luck writing good code in Unity. You need a workaround for even auto property serialization. Back to pattern matching it is. It’s the shortest reliable method I could find.

I’ve had that extension method around forever, and it works just fine for interfaces. Code more, complain less.