Attempting to make program wait before loading a new scene.

Hello.
We are a small group at a school having to make a quick prototype of what is basically a menu, and so I’ve created this code.
However, since it immediately loads the next scene, the Audio that is supposed to play never gets the chance to.

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class StartButton : MonoBehaviour {
public float TimeBetweenClicks = 0.3333f;
private float timestamp;

IEnumerator BeforeLoading(){
yield return new WaitForSeconds(0.3f);
}

// Update is called once per frame
void Update () {

}
void OnMouseOver () {
if (Time.time >= timestamp && (Input.GetKeyDown (KeyCode.Mouse0)) ){
this.GetComponent().Play();
print (“You started the game! Welcome!”);
BeforeLoading();
SceneManager.LoadScene(“HousePlan”);
}
}
}

the “If” statement with the timestamp is simply to keep the audio from playing a million time when the mouse button is held down.
I asked one of my teachers, but he had no time to look at it properly, and told me to write it like this before running off.

You’re almost there, but your BeforeLoading actually should be handled via StartCoroutine.

IEnumerator Loading() {
     yield return new WaitForSeconds(0.3f);
     SceneManager.LoadScene("HousePlan");
}

void OnMouseOver() {
    if (Time.time >= timestamp && (Input.GetKeyDown(KeyCode.Mouse0))) {
         this.GetComponent<AudioSource>().Play();
         print("You started the game! Welcome!");
         StartCoroutine(Loading);
   }
}

I’m not at my desk so not 100% I have it all correct, but that should be in the right direction.

1 Like

Thanks you for the answer byeasc!
I ended up simply changing the “onMouseOver” to “onMouseDown”, which meant I could drop the timestamps.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class StartButton : MonoBehaviour {

    private float timer = 0f;
    public bool X = false;
    // Update is called once per frame
    void Update () {
        if (X == true){
            timer += Time.deltaTime;
        }
        if (timer >= 0.3f){
            SceneManager.LoadScene("HousePlan");
        }

        if (timer >= 1f){
            X = false;
        }

    }

        void OnMouseDown(){
            X = true;
            this.GetComponent<AudioSource>().Play();
            print ("You started the game! Welcome!");

    }
}

By making a bool, I could make it so a timer counted down. Further, I could have made the 0.3f:

if (timer >= 0.3f){
            SceneManager.LoadScene("HousePlan");
        }

here its own public float, so that it could be easily changed.
Of course, by doing this you have to be careful to stop the timer by turning the bool X back to false, or else it’d go on forever. I don’t think it matters in my case, as I am loading a new scene, though.