- Home /
Function triggered when scene changes?
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!
hey you commented on $$anonymous$$e so...
well I got the gun to show but now I need it to move with the camera. Also I kinda need crosshair help.
Answer by Mike 3 · Aug 02, 2010 at 08:47 PM
There is an OnLevelWasLoaded(int : level) function, which should do exactly what you want
Sorry - I should rephrase my question. I want to know of a function that is called before a scene changes, in the scene the user is changing from.
Then no, there isn't one. You'll get an OnDisabled, but that's about it - The problem is that it's fired when you disable the script too (or make the gameobject inactive)
This is no longer the preferred way to do this. Check my answer for Unity5.4.
Answer by AndyMartin458 · Sep 21, 2016 at 03:20 PM
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
Answer by dil33pm · Nov 23, 2015 at 03:10 PM
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.
Answer by tinachanmakes · May 18, 2019 at 06:21 AM
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();
}
}
You’re doing additional computation every update. It’s much more efficient to subscribe to activeSceneChanged.
Your answer
Follow this Question
Related Questions
SerializedObject target has been destroyed. UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr) 9 Answers
Re-loading a scene but on the background older scenes are displayed 1 Answer
"Main" function? 3 Answers
Problem with Save Scene 1 Answer
UnloadSceneAsync() does not seem to work with additive scenes. 1 Answer