Retstart Key in C# or Javascript
I'm just a 3d designer who needs to finish a game project within a few weeks. I have designed the levels, now I would like to allow players to hit a key to restart the level if they fall down. Most probably "R" or "Enter". Could you please tell me how to make this script? Also, please mention should I attach the script to an empty object or the fps controller. I have 0 knowledge of coding so I'm depending on the coding veterans here. You will be mentioned later in my game as well.
Answer by corn · Jan 28, 2016 at 09:27 AM
What you need to know about is :
Input.GetKeyDown to detect if a key was pressed
SceneManager.GetActiveScene to know which scene is currently playing
SceneManager.LoadScene to load a scene
Scenes in Build Settings to add a scene to the Build Settings. At runtime, you can only load scenes that have been added to the Build Settings.
DontDestroyOnLoad to tell Unity not to destroy an object when loading scenes
So you just have to write a script that will reload the current scene when a certain key is pressed, and doesn't get destroyed when loading a scene. Then you attach this script to a GameObject in your first scene, so that it is accessible in every scene of your game.
using UnityEngine;
using UnityEngine.SceneManagement;
public class ReloadLevel : MonoBehaviour
{
// This function is only called once, when the object is initialized
void Awake()
{
// Tell Unity not to destroy the GameObject this script is attached to
// when loading a scene. That way, you only need to place an object
// with this script in your first scene, and it will stay in every
// scene.
DontDestroyOnLoad(gameObject);
}
// This function is automatically called every frame
void Update()
{
// Detect if R or Return were pressed
if (Input.GetKeyDown(KeyCode.R) || Input.GetKeyDown(KeyCode.Return))
{
// Get the active scene
Scene currentScene = SceneManager.GetActiveScene();
// To reload this scene, we have to use its name or its build index
// so that the Scene Manager knows what scene it needs to load.
// Get the Build Index of the active scene
int buildIndex = currentScene.buildIndex;
// Tell the Scene Mmanager to reload the scene corresponding to this
// Build Index in the Build Settings
SceneManager.LoadScene(buildIndex);
}
}
}
And voilà, it's actually pretty easy, right ?
Your answer
Follow this Question
Related Questions
R key= reset 3 Answers
How Checkpoint works? 1 Answer
How Can I Reset Values?(Unity3D) 0 Answers
Resetting Power up bar 0 Answers
Reset Key/Button in unity 5.2? 1 Answer