Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question why can GetComponent<Rigidbody>() be compared with Boolean values?

Discussion in 'Documentation' started by Aradozz, Apr 27, 2024.

  1. Aradozz

    Aradozz

    Joined:
    Apr 7, 2020
    Posts:
    2
    When we need to determine whether a rigidbody exists, we can use the following code:

    Code (CSharp):
    1.        if (GetComponent<Rigidbody>())
    2.         {
    3.          
    4.         }
    5.        
    6.        
    7.     if (GetComponent<Rigidbody>() == true)
    8.         {
    9.        
    10.         }
    GetComponent<Rigidbody> either returns null or Rigidbody, a Boolean value cannot be null, and also Boolean is value type while Rigidbody is reference type,

    So, why does the compiler not report an error?
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    8,450
    Last edited: Apr 27, 2024