Unity: Load scene on button press

A common task when building an application with Unity is to change to a different scene when the user is pushing a button. This is in itself a very easy task as Unity provides the SceneManager.LoadScene("MyScene"); method. Unfortunately, a lot of people end up having a lot of different scripts, with hard coded scene name strings in each of them essentially ending up with one script per button.

What I would like to share here is a very simple technique that allows creating just one generic script and assigning the scene to switch to in the inspector.

Step by step

  1. Create a new script named SceneLoader with the following content:
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneLoader : MonoBehaviour
{
    public void LoadScene(string sceneName)
    {
        SceneManager.LoadScene(sceneName);
    }
}

  1. In your scene, select the UI button element you want to use to change to a different scene to bring it up in the inspector.
  2. Add the SceneLoader.cs script as a script component to the button.
  3. Add a new entry to the On Click() list.
  4. In the new entry, drag the button object to the field showing None (Object).
  5. Select the SceneLoader -> LoadScene function
  6. Add the name of the scene you want to load in the parameter field.

Make sure that you drag the button object onto the None (Object) field of the On Click() list entry and not the SceneLoader() script. See the Troubleshooting section below.

And that’s it. Now you have a way of loading a different scene upon a button click by using just the inspector and without having to create a separate script each time.

Here’s a screeshot of the relevant sections of the button inspector after completing the steps outline above: Button Inspector Complete

Troubleshooting

The most common problem is that people tend to drag the script instead of the button object onto the None (Object) field of the entry in the On Click() list. In that case, the No Function dropdown will not list the SceneLoader.LoadScene() method: Button inspector with wrong object

comments powered by Disqus