Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

When can a Component's gameObject be null?

Discussion in 'Scripting' started by PanicEnsues, Nov 2, 2020.

  1. PanicEnsues

    PanicEnsues

    Joined:
    Jul 17, 2014
    Posts:
    187
    I'm getting some exception reports from external testers that have me stumped. Basically, I have a get;set property like this:

    Code (CSharp):
    1. public bool AIEnabled
    2. {
    3.     get { return gameObject.activeSelf; }
    4.     set { gameObject.SetActive(value); }
    5. }
    But there are occasional NullReference Exceptions on Target.get_AIEnabled ().

    I've done some tests to make sure that this code works on a disabled GameObject, and it's fine. What else in that get{} code could be null?

    Thanks for any suggestions!
     
  2. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,317
    If a gameObject is destroyed, it will be "null". Make sure that you're not calling AIEnabled on something that has previously been destroyed.
     
    PraetorBlue likes this.
  3. PanicEnsues

    PanicEnsues

    Joined:
    Jul 17, 2014
    Posts:
    187
    Good point! I thought I was checking for that before calling that Property, but it turns out I was actually testing to see if the component was null, not the GameObject.

    Thanks!
     
    Madgvox likes this.