- Home /
When does Instantiate return ?
I have a Loader script that basically instantiates the GameManager singleton if it doesn't already exist. Thing is, I have a blank Scene at the start to make all the loading, and I want to load the next scene when the GameManager is done doing its things. I have the following code :
public class Loader : MonoBehaviour
{
public GameManager gameManager;
void Awake()
{
if (GameManager.instance == null)
{
Instantiate(gameManager);
gameManager.LoadNextScene();
}
}
}
And this is the GameManager :
public class GameManager : MonoBehaviour {
public static GameManager instance = null;
private XMLReader xmlReader;
private void Awake()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
xmlReader = GetComponent<XMLReader>();
Initialize();
}
private void Initialize()
{
xmlReader.Reader();
}
public void LoadNextScene ()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
I want to stay on the first Loading Scene until the Reader() function is done, and I don't know if this is working right now.
When does Instantiate() return ? Is it when the code in the instantiated object's Awake returns ? Is it before even calling Awake on the object ?
If it is the latter, how to delay a function call until another function is finished with its execution ?
I edited the question to be clearer in the actual question I'm curious about. I want to know when Awake returns to know if what I'm doing would work, or if I need to get into other solutions ?
Answer by Captain_Pineapple · May 16, 2018 at 05:36 AM
Hey there,
for your loading problem you should perhaps look into Asynchronous Scene Loading. That might solve your problems, you can still do stuff while loading and you can see when its finished by following their code example in the docs.
For delaying a function call i mostly just set a flag in the said function call and check for that flag in for example the update fuction. Though there are probably better ways.
Hope this helps.
I know about asynchronous loading, but here I don't want to preload Scene2 ; I want to make sure I'm done loading data from the xml file in my game manager in Scene1 before going into Scene2, because Scene2 needs the data to be there.
Answer by sum1nil · May 16, 2018 at 05:38 AM
This may be of help with the second part of your question.
private void Initialize()
{
private static object lockObject = new object();
lock(lockObject) {
// ... code goes here...
xmlReader.Reader();
}
}
https://stackoverflow.com/questions/1897265/blocking-a-function-call-in-c-sharp
Can I use that object to lock conflicting calls to different functions ?
i.e. lock the object when I call Reader and prevent LoadNextScene to be called when the object is locked ?