Gameobject not null at start but in function it is.

Dear Unity,

I have a nullpointer exception and am not really sure why I am getting this. I have a script with 2 objects connected to it. Spatula and Fryingpan which I set to nonactive at the initialization of the script start as followed:

  if (RecepScenarioObjectHandelerNull())
    {
        InitializeReceptScenarioObjectHandler();
    }

→ Then it initializes like overe here

  void Start () {
    if (!IfSpatulaAndFryingPanNull())
    {
        Spatula.SetActive(false);
        FryingPan.SetActive(false);
    }
}

This works perfectly and disabled the game objects right from the start which I want. But when I want to activate the gameobjects for use with the following function I get a nullpointer:

public bool IfSpatulaOrFyingPanActive()
{
    if (IfSpatulaAndFryingPanNull())
    {
        System.Diagnostics.Debug.WriteLine("One of the objects is null");
    }
    else if (Spatula.activeSelf == true || FryingPan.activeSelf == true)
    {
        return true;
    }
    return false;
}

Even if I do not disable the objects in the beginning the debugging shows me that the objects are null and I have no clue why. I do not move to another scene or close a script.

Side note: I added the gameobjects as publics and added the objects in unity as follows:

90050-imageunity.png

Does anyone know what the problem could be?

Kr,

You’re adding in another component of the same type, that’s where the issue is. When you add in a new component, all the values inside that class are initialised to the default. In this case, the default values for Spatula and FryingPan are indeed null, hence your null reference exception. The one that you assigned in the editor has all of the references already sorted out, hence why they aren’t null when the component starts. You need to use the gameobjects Get Component method to get the component instance, not Add Component. This instance will be the one you tweaked in the editor, the one that is on the gameobject.

Hi! Just a small thing, but the logic of your method for checking for nulls is named using ‘and’:

IfSpatulaAndFryingPanNull()
however, your code is using the ‘or’ test, not ‘and’:
return Spatula == null || FryingPan == null;

This could cause some confusion if the two aren’t in agreement :wink: