Home >Backend Development >C++ >Why Does My Unity Game Manager Script Only Run Once, and How Can I Make It Persistent Across Scenes?
Unity Game Manager: Cross-scenario persistence issues and solutions
Question:
Game Manager scripts designed to be persistent across scenes will only be executed once on project initialization, even if present in all scenes.
Reason:
Every Unity project requires a "preload scene" as the central hub for persistent objects and systems. This scenario must be specified as scenario 0 in the build settings.
Solution:
Create a preloaded scene:
Add preloaded game object:
Apply DontDestroyOnLoad:
Place common behavior in preload scene:
Find components in other scenes:
To access these persistent components from other scenes, you can use the static method "Object.FindObjectOfType
<code class="language-C#">SoundEffects sound = Object.FindObjectOfType<SoundEffects>(); GameState state = Object.FindObjectOfType<GameState>();</code>
Optional optimization:
To reduce code duplication, consider using the following global script:
<code class="language-C#">public static class App { public static SoundEffects SoundEffects { get; private set; } public static GameState GameState { get; private set; } static App() { GameObject appObject = GameObject.Find("__app"); SoundEffects = appObject.GetComponent<SoundEffects>(); GameState = appObject.GetComponent<GameState>(); } }</code>
Using this script you can access these components using a simplified syntax:
<code class="language-C#">App.SoundEffects.PlayExplosion(); App.GameState.CurrentLevel = 5;</code>
Development convenience:
In order to improve development efficiency, you can consider adding a script to the "preload" scene. If the "__app" object does not exist, the "preload" scene will be automatically loaded during project initialization. This ensures that the game starts from the "preload" scene every time "Play" is clicked.
The above is the detailed content of Why Does My Unity Game Manager Script Only Run Once, and How Can I Make It Persistent Across Scenes?. For more information, please follow other related articles on the PHP Chinese website!