Search code examples
c#unity-game-enginetransitionscenescene-manager

How to change scenes in Unity with any input (key pressed or mouse clicked)?


I'm trying to change the scene with any key pressed or mouse clicked but it doesn't seem to be giving any response in-game.

I've tried the most common solution to this on the internet :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ForMainMenu : MonoBehaviour

{

    public 

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.anyKeyDown)
        {
            SceneManager.LoadScene("Main menu");
        }
    }

}

I'm not sure what to apply the script on either. Right now, the script is applied to a game object.

The scenes in my assets: https://i.sstatic.net/DoUn6.jpg


Solution

  • Firstly, like @TehMightyPotato has explained, remove the lonely "public" keyword before void Start(). Then in the menu, click on Build and make sure to click on "Add Open Scenes" to add all the scenes under "Scenes in Build". Then in the script, change update function as below:

    void Update()
        {
            if (Input.GetKeyDown(KeyCode.A))
            {
                SceneManager.LoadScene("Main menu");
            }
        }
    

    Try to add this script on an active gameObject in the scene.