using UnityEngine;
public class RestartGame : MonoBehaviour
void (input.GetKeyDown(varKeyInput)
{
Application.LoadLevel(?);
}
//I know its wrong
using UnityEngine;
public class RestartGame : MonoBehaviour
void (input.GetKeyDown(varKeyInput)
{
Application.LoadLevel(?);
}
//I know its wrong
If I press key “R” game restart
There are two ways of doing it; asynchronously and synchronously. The latter will hang the application, but it’s way fewer steps to get working. So I’ll put that one first and then talk about an async call later.
First, if you haven’t already, add your scene to the list of scenes by going File:Build Settings and dragging your scene into the box list.
Second, in your script, write something like the following.
using UnityEngine;
using SceneManagement;
public class RestartGame : MonoBehaviour
{
void Update()
{
if(Input.GetKeyDown(KeyCode.R))
{
//Application.LoadLevel is depreciated; use the scene manager function
//that you get from 'using SceneManager'
//You can see there are a few overloads for this function; you can pass a string (name) or number for the scene.
SceneManager.LoadScene(0);
}
}
}
That would be the way that (if you have a massive scene to move to) will hang your application for some time. Most people will be okay with waiting a little bit, as long as they know they haven’t crashed, so the other alternative would be preferable: LoadSceneAsync
bool m_transitioning = false;
void Update ()
{
if(Input.GetKeyDown(KeyCode.R) && !m_transitioning)
{
StartCoroutine(ILoadLevel());
}
}
//Google Unity Coroutines if you are unsure about this, mate
IEnumerator ILoadLevel()
{
//Don't forget to lock the coroutine from multiple calls.
m_transitioning = true;
//Calling this gets you the progress, completion and some stuff like that to tinker with while loading.
AsyncOperation operation = SceneManager.LoadSceneAsync(0);
//From here you can say something like - while(!operation.isDone) progressText = operation.progress;
//Finally, change scenes once we're done loading.
yield return operation;
}
If you have any other queries, don’t hesitate to reply.
-edit-
SceneManagement, not SceneManager.
thx
To add to @Jam0kid 's post, you can also use SceneManager.GetActiveScene() to get the current scene and then pass it’s name to the SceneManager.LoadScene(Async()) function. That way you don’t need to use magic numbers to reload the scene.