Search code examples
c#unity-game-engineshort-circuitingshort-circuit-evaluation

Short Circuit Evaluation with Components in Unity


I have a line of code: Rigidbody rigidbody = go.GetComponent<Rigidbody>() ? go.GetComponent<Rigidbody>() : go.AddComponent(typeof(Rigidbody)) as Rigidbody; where go is a GameObject. When I try to simplify this using short circuit evaluation to Rigidbody rigidbody = go.GetComponent<Rigidbody>() || go.AddComponent(typeof(Rigidbody)) as Rigidbody; it gives the error CS0029: Cannot implicitly convert type 'bool' to 'UnityEngine.Rigidbody'.

Am I doing the short circuit evaluation incorrectly here? Is it possible to do this using short circuit or must I use my longer solution.

Any help or advice is appreciated. Thanks.


Solution

  • The scenario you’ve described here is the reason Unity have also provided TryGetComponent<T>(out T component).

    You would use it like this:

    if ( !go.TryGetComponent<Rigidbody>( out var rigidbody ) )
        rigidbody = go.AddComponent<Rigidbody>() as Rigidbody;
    // rigidbody is now set ...
    
    

    This protects you from the quirk of Unity objects appearing to be non-null under certain conditions, and satisfies the Unity engineers requests that you not use the null-conditional/coalescing operators.