Search Unity

MissingReferenceException when nullchecking.

Discussion in 'Scripting' started by Bonahona, Jun 19, 2019.

  1. Bonahona

    Bonahona

    Joined:
    Jan 23, 2015
    Posts:
    4
    In a MonoBehaviour derived class I've written I have the following method.
    Code (CSharp):
    1.         public void DestroyContainer()
    2.         {
    3.             foreach(var target in Targets) {
    4.                 target.WearOffEffects(CurrentEffect.TargetEffects, Source);
    5.                 target.WearOffEffects(TargetEffects, Source);
    6.             }
    7.  
    8.             if (gameObject != null) {
    9.                 GameObject.Destroy(gameObject);
    10.             }
    11.         }
    At first it occasionally gave me a NullPointerException when trying to destroy the game object so I've added a null check for it. Now the null check throws a MissingReferenceException and I just can't understand what is happening.
     
  2. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    hmm, it sounds like line 3 or 4 is giving that error, not line 8 or 9. Are you sure you have the right culprit? A missing reference exception fires when an inspector variable isn't assigned but you try to access it, usually.
     
  3. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,188
    It is impossible to tell from the code snippet, but this sounds very much like an issue that can arise, when GameObjects are destroyed on the C++ side of the engine and you are still keeping a C# reference to this GameObject.

    In general, Unity handles this issue well and provides helpful error logs, but maybe something more complex is happening here. When you call GameObject.Destroy Unity destroys the C++ GameObject. When you now access a GameObject reference it usually logs an error that the object is already destroyed and returns a C# fake null, which makes null checks work. But again, something about your setup may be more complex.
     
  4. Bonahona

    Bonahona

    Joined:
    Jan 23, 2015
    Posts:
    4
    Yes, I know that's the line causing the trouble. It was the line pointed out in the console.
    I've solved the problem temporarly by just wrapping the null checking and GameObject.Destroy() statements in a try-catch block but would like to know the reason why this throws when it really shouldn't.
     
  5. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    I've edited my first post to include the explanation as to why this is happening.
    Edit: Whoops never mind. I didn't notice that the Destroy() call was outside of the loop.