Reputation: 541
Could someone please point me to a tutorial that can make a global "back button" function in unity?
Currently I am able to override it via "Update" function with this code
if (Input.GetKeyDown(KeyCode.Escape))
{
//Do something you need
Debug.Log("Back button is pressed");
}
The drawback, however, I need to attach this function in one active "Gameobject" in every scene.
Is there perhaps any method to make this function globally and therefore this "Update" function always listening in every scene?
Upvotes: 2
Views: 2740
Reputation: 17085
You can attach this script to a gameObject in your initial scene.
void Awake(){
DontDestroyOnLoad(this.gameObject);
}
void Update(){
if (Input.GetKeyDown(KeyCode.Escape))
{
//Do something you need
Debug.Log("Back button is pressed");
}
}
DontDestroyOnLoad
causes the game object to persist after leaving the scene.
In order to change the scene, you can call SceneManager.LoadScene
with one of these options:
Single
Closes all current loaded scenes and loads a scene.Additive
Adds the scene to the current loaded scenes.As in
SceneManager.LoadScene("OtherSceneName", LoadSceneMode.Single);
One design pattern is to have an initial scene (named e.g. persistantScene or bootstrapper) in which persistent objects such as the first script above exist. it navigates to the next scene with Single
option, keeping persistent (DontDestroyOnLoad) objects through the next scene while discarding other objects which belong only to the previous scene.
Moreover, you can make it a singleton if you need easy access:
public static MyMonobehaviour Instance;
void Awake(){
Instance = this;
DontDestroyOnLoad(this.gameObject);
}
void Update(){
...
}
Upvotes: 4