- Tutorials
- User Interface (UI)
- Creating a scene selection menu
Creating a scene selection menu
Checked with version: 4.6
-
Difficulty: Beginner
In this training session we'll create a menu using the UI tools from which we can choose and load a scene. We'll do some simple scripting to achieve this including looking at Application.LoadLevel, Object.DontDestroyOnLoad and Application.LoadLevelAdditive.


Creating a scene selection menu
Beginner User Interface (UI)
Script to load a scene when clicked.
LoadOnClick
Code snippet
using UnityEngine;
using System.Collections;
public class LoadOnClick : MonoBehaviour {
public GameObject loadingImage;
public void LoadScene(int level)
{
loadingImage.SetActive(true);
Application.LoadLevel(level);
}
}
The game object this script is attached to will not be destroyed when a new scene is loaded.
DontDestroy
Code snippet
using UnityEngine;
using System.Collections;
public class DontDestroy : MonoBehaviour {
// Use this for initialization
void Awake () {
DontDestroyOnLoad(gameObject);
}
}
Script to change the music playing after a scene is loaded.
ChangeMusic
Code snippet
using UnityEngine;
using System.Collections;
public class ChangeMusic : MonoBehaviour {
public AudioClip level2Music;
private AudioSource source;
// Use this for initialization
void Awake ()
{
source = GetComponent<AudioSource>();
}
void OnLevelWasLoaded(int level)
{
if (level == 2)
{
source.clip = level2Music;
source.Play ();
}
}
}
Script to add the selected scene without destroying objects from the current scene.
LoadAdditive
Code snippet
using UnityEngine;
using System.Collections;
public class LoadAdditive : MonoBehaviour {
public void LoadAddOnClick(int level)
{
Application.LoadLevelAdditive(level);
}
}
Script to load a scene in the background while the current script plays (Pro only).
ClickToLoadAsync
Code snippet
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ClickToLoadAsync : MonoBehaviour {
public Slider loadingBar;
public GameObject loadingImage;
private AsyncOperation async;
public void ClickAsync(int level)
{
loadingImage.SetActive(true);
StartCoroutine(LoadLevelWithBar(level));
}
IEnumerator LoadLevelWithBar (int level)
{
async = Application.LoadLevelAsync(level);
while (!async.isDone)
{
loadingBar.value = async.progress;
yield return null;
}
}
}