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

null GameObject

Discussion in 'Scripting' started by Slabada, May 12, 2022.

  1. Slabada

    Slabada

    Joined:
    May 2, 2021
    Posts:
    50
    Hello, tell me, please, I have a Gameobject variable in my code, it is empty, an object will be added there during the game.
    How do I make sure that there is no error due to the fact that Gameobject is empty?
    I searched the Internet, but I didn't find any clear information for myself.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    Make sure the variable is not null before doing something with it:
    Code (CSharp):
    1. if (myVariable != null) {
    2.   // Do stuff with myVariable here.
    3. }
     
    Bunny83, Slabada and Kurt-Dekker like this.
  3. Akuramuzda

    Akuramuzda

    Joined:
    Apr 26, 2021
    Posts:
    5
    Use the implicit conversion UnityEngine.Object to bool.
    Code (CSharp):
    1. if (obj) // obj must be a class derived from UnityEngine.Object
    2. {
    3.     // the object exists.
    4. }
     
    Bunny83, Slabada and PraetorBlue like this.
  4. Slabada

    Slabada

    Joined:
    May 2, 2021
    Posts:
    50
    Thank you all for your help :)