Edit: Here is some important update:
I have found out that the script's Start and Awake voids are called, but AFTER the script is used by some other script. So the problem here is that the gameobject that hosts "OtherScript" is initialized after the gameobject which has a "MainScript" attached and which holds a reference to "OtherScript".
I hope I could explain it well.
If just the one gameobject was initialized before the other, everything would be fine. I will investigate now if I can change the intialization order.
Original post:
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:
I have then put a reference to empty GameObject to the Cube's "OtherScript" slot:
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?
GameObject
? \$\endgroup\$