Skip to content

Instantly share code, notes, and snippets.

@samsheffield
Created September 28, 2021 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samsheffield/bf5fc32420340b419e23822e3bb5399f to your computer and use it in GitHub Desktop.
Save samsheffield/bf5fc32420340b419e23822e3bb5399f to your computer and use it in GitHub Desktop.
Load a scene with a keypress
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; // Add Scene Management
public class SwitchScene : MonoBehaviour
{
// Important: Don't forget to add the next scene to your project's Build Settings
// Set the name of the Scene you want to switch to in the Inspector
public string nextScene;
// Keys that can be set in the Inspector
public KeyCode switchKey = KeyCode.Space;
public KeyCode quitKey = KeyCode.Escape;
// Update is called once per frame
void Update()
{
// If this key is pressed and released...
if(Input.GetKeyUp(switchKey) == true)
{
// Load next scene
SceneManager.LoadScene(nextScene);
}
// If this key is pressed
if (Input.GetKeyUp(quitKey) == true)
{
// Quit game
Application.Quit();
}
}
}
Here is a bonus Unity example for 2D Game Design F21. Let me know what else you need!
======================================================================================
SWITCH SCENE WITH A KEY PRESS
Full example: SwitchScene.cs
Important:
1. Don't forget to add the next scene to your project's Build Settings
// If this key is pressed and released...
if(Input.GetKeyUp(switchKey) == true)
{
// Load next scene
SceneManager.LoadScene(nextScene);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment