Variable Becoming null only inside functions

Hi all,

This problem has thrown me for a loop. My code worked fine until I turned a certain object into a prefab. Now the things I instantiate in it become null exclusively inside of functions.

I have a list of Stage objects called stages. In the Awake() function I load them and set the current stage to stages[0].

void Awake()
    {
        stageHandler = GameObject.Find("StageHandler").GetComponent<StageHandler>();
        worldID = 1;
        loadStages();
        setStage(stages[0]);
        Debug.Log("Awake: " + stages.Count);
    }

The debug line says there are 5 Stages in the list.

The Start, Update, and OnEnable functions also say there are 5.

void Start () {
        Debug.Log("Start: " + stages.Count);
    }
void OnEnable()
    {
        Debug.Log("OnEnable: " + stages.Count);
    }
    void Update()
    {
        Debug.Log("Update: " + stages.Count);
    }

But as soon as I click the button to move up one stage…

    public void moveUpOneStage()
    {
        Debug.Log("MoveUp: " + stages.Count);
        int location = stages.IndexOf(currentStage);
        Debug.Log(currentStage);
        if(stages.Count > location)
        {
           setStage(stages[location + 1]); 
        }
    }

    public void setStage(Stage s)
    {
        if(currentStage != null)
        {
            currentStage.setActive(false);
        }
        foreach(Stage stage in stages)
        {
            stage.setActive(false);
        }
        s.setActive(true);
        currentStage = s;
    }

The debug line shows this:

71229-stagecount.png

And then it returns to 5 in the Update calls! Am I doing something really stupid and just don’t see it?

The “stages” list appears to be fine, it’s the currentStage variable that’s apparently broken.

My best guess is that it’s never properly set to anything, that’s why Debug.Log on the currentStage returns null. Consequently, getting IndexOf of the null object returns “-1” index if I’m not mistaken. Don’t forget to set/assign/initialize your currentStage variable.

I am a bit stumped about the “MoveUp: 0” output, though… Is all the provided code within one same script? Could you perhaps post the entire script, and give it a brief commentary to see what gets called in what scenario?

I figured it out! Thanks to Eudaimonium for helping me look in the right direction. The button was accessing the prefab instead of the instantiated prefab. I worked around this by writing some code for the button to find the instantiated prefab after it had been created with this:

world = GameObject.FindGameObjectWithTag(“World”).GetComponent();