1

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.

Jahill
  • 78
  • 1
  • 7

2 Answers2

1

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.

Milan Egon Votrubec
  • 3,696
  • 2
  • 10
  • 24
0

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 ??.

Jahill
  • 78
  • 1
  • 7
  • 1
    Avoid using null coalescing operator on unity objects, as it will not always provide the value you want. This is due to unitys override of the equality operator for Object. The reference for [Object](https://docs.unity3d.com/2020.1/Documentation/ScriptReference/Object.html) states this clearly: `This class doesn't support the null-conditional operator (?.) and the null-coalescing operator (??).` – hijinxbassist Jan 10 '23 at 22:00