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.
The scenario you’ve described here is the reason Unity have also provided
TryGetComponent<T>(out T component).You would use it like this:
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.