Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Check if object is null

Discussion in 'Scripting' started by TRALLALAL, Jul 17, 2014.

  1. TRALLALAL

    TRALLALAL

    Joined:
    Sep 7, 2013
    Posts:
    132
    I tried both

    Code (CSharp):
    1.  
    2. if(object)
    3.  
    4. and
    5.  
    6. if(object != null)
    but if it doesn't exist Unity always throws an exception, is it normal?
     
  2. Patico

    Patico

    Joined:
    May 21, 2013
    Posts:
    886
    Second version is more correct, but it should not thow an exception.
     
  3. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
  4. TRALLALAL

    TRALLALAL

    Joined:
    Sep 7, 2013
    Posts:
    132
    Object was an example of course
    Code (CSharp):
    1.  
    2. if (secondaryWeaponExists.secondaryWeapon != null)
    3. {
    4.        if (Input.GetKeyDown(KeyCode.Alpha2) && !keyPressed)
    5.        {
    6.            StartCoroutine(waitForSwitch());
    7.            weaponActive = !weaponActive;
    8.        }
    9. }
     
  5. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    I assume secondaryWeaponExists does not exist. Therefore, secondaryWeaponExists.secondaryWeapon throws an error because you are trying to access something which is null.
     
  6. TRALLALAL

    TRALLALAL

    Joined:
    Sep 7, 2013
    Posts:
    132
    Uhm what if secondaryWeapon is static?
     
  7. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    As long as secondaryWeaponExists is an instance and that instance is null, you can not access any of its members.

    If you are trying to check a static variable use the class name rather than the instance.
     
  8. TRALLALAL

    TRALLALAL

    Joined:
    Sep 7, 2013
    Posts:
    132
    Thanks.
     
  9. Patico

    Patico

    Joined:
    May 21, 2013
    Posts:
    886
    Just add one more check:
    Code (csharp):
    1.  
    2. if (secondaryWeaponExists != null && secondaryWeaponExists.secondaryWeapon != null)
    3. {
    4.   ...
    5. }
     
    Last edited: Jul 18, 2014
    TRALLALAL likes this.
  10. TRALLALAL

    TRALLALAL

    Joined:
    Sep 7, 2013
    Posts:
    132
    Thanks!