Skip to main content
2 of 3
I have added some code to check if Start or Awake have occured
tmighty
  • 919
  • 1
  • 15
  • 42

Awake and Start not called for script

Edit: Currently, the code works fine. I'm not sure why it didn't work when I posted the problem.

I will investigate it first.

I have a complex scenario which I have reduced to the following problem:

I have a Cube in my Unity scene. This cube has the following script on it:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MainScript : MonoBehaviour
{
    public OtherScript TheOtherScript;

    public void OnGUI()
    {
        if (GUI.Button(new Rect(0, 0, 50, 50), "Load something"))
        {
            this.TheOtherScript.LoadFile();
        }
    }
}

The script "OtherScript" looks like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OtherScript : MonoBehaviour
{
    private string _sPath;

    public bool HasBeenInitialized = false;

    public void Awake()
    {
        _sPath = Application.persistentDataPath + "/somefilename.dat";
        this.HasBeenInitialized = true;//indicator that Awake or Start have occured
    }
    public void Start()
    {
        _sPath = Application.persistentDataPath + "/somefilename.dat";
        this.HasBeenInitialized = true;//indicator that Awake or Start have occured
    }

    public void LoadFile()
    {
        if (_sPath == null)
        {
            Debug.Break();
        }
        //do something with _sPath
    }
}

I have created an empty GameObject to my scene, and I have added such a script to it:

enter image description here

I have then put a reference to empty GameObject to the Cube's "OtherScript" slot:

enter image description here

The problem that I'm experiencing is that "TheOtherScript"'s start / awake has not been called when this button is pressed:

    if (GUI.Button(new Rect(0, 0, 50, 50), "Load something"))
    {
        if (!this.TheOtherScript.HasBeenInitialized)
        {
            Debug.Break();//The script hasn't processed Start or Awake yet. Why???
        }

        this.TheOtherScript.LoadFile();
    }

Neither Awake nor Start is called on this script.

Which event could I react to in this case for initialization?

tmighty
  • 919
  • 1
  • 15
  • 42