- Home /
 
               Question by 
               MrHighway1992 · Oct 13, 2018 at 04:08 PM · 
                unity 5uibuttonscene-loadingrandom.range  
              
 
              Loading a scene after a random amount of time.
I have a simple code that generates a random number then loads a scene based on the number generated
 public class RandomGenerator : MonoBehaviour
 
 {
   
     public int Number;
 
     public void RandomGenerate()
     {
         Number = Random.Range(1, 22);  
     }
     private void Update()
     {
         if ((Number == 1) || (Number == 2))           
         {
             SceneManager.LoadScene("Shuffle");
         }
 
I want to add a random delay before the scene is loaded say once the number has been generated wait 5 to 20 seconds before loading the chosen scene.
Thank you for any help.
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by Matthew_Ostil · Oct 13, 2018 at 04:17 PM
You can use a coroutine:
 using System.Collections;
 
 public class RandomGenerator : MonoBehaviour
 {
     public int Number;
 
     public void RandomGenerate()
     {
         Number = Random.Range(1, 22);
         StartCoroutine(LoadScene(Number));
     }
 
     IEnumerator LoadScene (int sceneNumber)
     {
         float secondsToWait = Random.Range(5, 20);
         yield return new WaitForSeconds(secondsToWait);
 
         if ((sceneNumber == 1 || sceneNumber == 2))
         {
             SceneManager.LoadScene("Shuffle")
         }
 
         // etc.
     }
 }
That works great thanks, would it be possible to add like a "pending" scene while waiting for the timer ?
   IEnumerator LoadScene (int sceneNumber)
      {
          Scene$$anonymous$$anager.LoadScene("Pending");
          float secondsToWait = Random.Range(5, 20);
          yield return new WaitForSeconds(secondsToWait);
  
          if ((sceneNumber == 1 || sceneNumber == 2))
          {
              Scene$$anonymous$$anager.LoadScene("Shuffle")
          }
  
          // etc.
      }
yeah, I tried that, it just loads the pending scene and cancels out the other scenes from loading =[
Your answer
 
 
             Follow this Question
Related Questions
UI button in Panel not clickable 2 Answers
Unity UI Button behaviour changes in WebGL 0 Answers
Unity 5 Controlling Animation with UI Button 0 Answers
Button position scaling weird 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                