How to instantiate objects upon scene load?
Hello, I have one GameObject that basically holds everything the game needs to run in a scene. This includes:
Scripts
Camera
UI
I've gotten the mod system to work perfectly, but there's one issue that is a bit confusing. When a person creates a map mod, I don't want them to have access to this GameObject, I don't even want to deal with it when I'm making a new map.
So I need a way to Instantiate this when the Scene loads. Is this possible? :)
Answer by NinjaISV · Nov 17, 2018 at 08:27 PM
Yes, this is quite easy to do. The best approach would be to have a static class (called SceneManager or something similar) which instantiates the prefab upon loading a new scene.
The script would look something like:
public static class SceneManager {
private static bool initialized = false;
// ensure you call this method from a script in your first loaded scene
public static void Initialize () {
if (initialized == false) {
initialized = true;
// adds this to the 'activeSceneChanged' callbacks if not already initialized.
UnityEngine.SceneManagement.SceneManager.activeSceneChanged += OnSceneWasLoaded;
}
}
private static void OnSceneWasLoaded (UnityEngine.SceneManagement.Scene from, UnityEngine.SceneManagement.Scene to) {
// do instantiate work here
}
}
Sources: https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-activeSceneChanged.html
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Your answer
Follow this Question
Related Questions
SceneManager.sceneLoaded returns scene.isLoaded as false, is this intended? 1 Answer
Switching back and fourth between scenes help (script) 0 Answers
Scene created from a script gives an error when tried to load 1 Answer
LoadScene will only work from first scene 1 Answer
LoadScene not working 0 Answers