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.
CodePudding user response:
Ok, so I forgot about null coalescing which is exactly the solution I am looking for. My mind is stuck on JavaScript where short circuit evaluation will act similarly to null coalescing, but C# has no such concept.
Essentially my issue was using ||
instead of ??
.
CodePudding user response:
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.