Skip to content

Scene and game state

A scene is a saved set of GameObjects. A game usually has several: a menu scene, gameplay scenes, and so on. Use SceneManager to load, save, and switch them.

There is no separate “world script”. Any MonoBehaviour can manage scene flow by calling SceneManager.

SceneManager.LoadScene takes a path and a mode. Single unloads the other scenes first. Additive keeps them loaded.

using Kolpa.Engine;
public class LevelPortal : MonoBehaviour
{
public string NextScenePath = "scenes/level2.scene";
public void Enter()
{
SceneManager.LoadScene(NextScenePath, SceneManager.LoadSceneMode.Single);
}
}

SceneManager raises three events from the native host:

public class SceneWatcher : MonoBehaviour
{
public override void OnCreate()
{
SceneManager.sceneLoaded += OnSceneLoaded;
SceneManager.activeSceneChanged += OnActiveChanged;
}
public override void OnDestroy()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
SceneManager.activeSceneChanged -= OnActiveChanged;
}
private void OnSceneLoaded(Scene scene, SceneManager.LoadSceneMode mode)
{
Log($"loaded {scene.name}");
}
private void OnActiveChanged(Scene previous, Scene next)
{
Log($"active scene {previous.name} -> {next.name}");
}
}

Always unsubscribe in OnDestroy. Static events outlive the script instance.

Scene scene = SceneManager.CreateScene("level3");
SceneManager.SetActiveScene(scene);
SceneManager.SaveScene(scene, "scenes/level3.scene");

Read sceneCount, GetSceneAt(index), GetActiveScene(), and FindScene(name) to inspect loaded scenes. UnloadScene(scene) removes one.

GameObject has static lookups that search the loaded scene:

GameObject player = GameObject.Find("player");
GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");

See Communication to reach components and script instances.

Previous: Gameplay scripts: logic on one GameObject.

Next: Communication: call other scripts and read components.