Back to main menu after 3s from show ui text
Hi, I made game with collectibles and after collect all of them on the screen we can see "you won" which is UI Text. I'd like to back to main menu after 3 seconds from this text. This UI Text is including all game scene. In my build settings main menu has number 2 - for easier make code for me. How then can I do it, with script I guess?
Answer by corn · May 22, 2016 at 07:15 AM
Easiest way to do it would be to attach a script to your text, and only activate your text's GameObject when you show it, so that you can call the code to load the scene with the OnEnable callback. To wait for 3s, you need to use a Coroutine.
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class LoadScene : MonoBehaviour
{
[SerializeField]
private int m_SceneIndex = 2;
[SerializeField]
private float m_DelayBeforeLoad = 3f;
private void OnEnable()
{
StartCoroutine(WaitAndLoadScene(m_SceneIndex, m_DelayBeforeLoad));
}
private IEnumerator WaitAndLoadScene(int sceneIndex, float delay)
{
yield return new WaitForSeconds(delay);
SceneManager.LoadScene(sceneIndex);
}
}
However, it would be better to write a public function that you would call right after showing the text, in which case you'd need to replace private void OnEnable()
by public void Load()
.
I copied and pasted this script but game changes to scene 2 immediatly after 3 seconds ins$$anonymous$$d after this ui text show up, any ideas?
After replace private void OnEnable()
to public void LoadScene()
I get error "'LoadScene': member names cannot be the same as their enclosing type".
If you use OnEnable, you need to attach the script to the GameObject to which the Text is attached, and disable it. You have to enable it only when the game is over.
As for LoadScene(), my bad, you cannot have a public function with the same name as the class, unless it's a constructor. Just call it Load() or whatever.
I made it on my own with different way, exactly ins$$anonymous$$d after "you won" game takes you to main menu after 3 seconds I made 2 buttons for go to main menu and exit from game. But of course thank you for help , you got Accept :)