Is there a function or MonoBehaviour in Unity which is triggered before a scene changes in the scene that is being changed from? (such as when Application.LoadLevel() is called) Something like the opposite of the Awake() function?
Thank You!
Is there a function or MonoBehaviour in Unity which is triggered before a scene changes in the scene that is being changed from? (such as when Application.LoadLevel() is called) Something like the opposite of the Awake() function?
Thank You!
In Unity5.4 (and maybe 5.3?), OnLevelWasLoaded
is no longer listed in the documentation.
MonoBehaviour documentation
You need to subscribe to the event SceneManager.activeSceneChanged
instead.
SceneManager-activeSceneChanged documentation
You can create a dummy gameObject and write your code in its onDestroy()
function. When the scene changes, onDestroy()
will be called and your code will be executed.
There is an OnLevelWasLoaded(int : level) function, which should do exactly what you want
I used this to reposition my player back at its original position whenever a scene changed. It would detect a change through the update function.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Resetter : MonoBehaviour
{
Vector3 originalPos;
Scene m_Scene;
Scene f_Scene;
void Start()
{
m_Scene = SceneManager.GetActiveScene();
originalPos = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z);
}
// Update is called once per frame
void Update()
{
m_Scene = SceneManager.GetActiveScene();
if (m_Scene.buildIndex != f_Scene.buildIndex)
{
transform.position = originalPos;
}
f_Scene = SceneManager.GetActiveScene();
}
}