How to make a delay before an action?
Hello! I'm new to Unity and C#. Need some help with making a delay before doing something.
I need to wait for 3 seconds before application runs next scene.
Here is my script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed;
public Text pickupsLeftText;
public Text winText;
public string nextLevel;
private Rigidbody rb;
private int pickupsLeftNum;
private int pickups;
private bool levelFinished;
void Start ()
{
rb = GetComponent<Rigidbody>();
GameObject[] pickupsOnLevel = GameObject.FindGameObjectsWithTag ("Pickup");
pickups = pickupsOnLevel.Length;
pickupsLeftNum = pickups;
SetPickupsLeftText ();
winText.text = "";
levelFinished = false;
}
void Update () {
if (levelFinished) {
StopCoroutine ("NextLevel");
StartCoroutine ("NextLevel");
}
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pickup"))
{
other.gameObject.SetActive(false);
pickupsLeftNum = pickupsLeftNum - 1;
SetPickupsLeftText ();
}
if (other.gameObject.CompareTag("Speed Up"))
{
other.gameObject.SetActive(false);
speed = speed * 2;
}
}
void SetPickupsLeftText ()
{
pickupsLeftText.text = "Pickups left: " + pickupsLeftNum;
if (pickupsLeftNum == 0) {
levelFinished = true;
winText.text = "You win!";
NextLevel ();
}
}
void NextLevel ()
{
yield WaitForSeconds(3);
Application.LoadLevel (nextLevel);
}
}
I need to have 3 seconds delay in NextLevel function. Thank you!
P.S. Could you please advice me some websites to learn C#?)
Answer by vaniko2003 · Aug 23, 2017 at 06:26 PM
You just have to go to a new void in time with Invoke, like:
if(input.GetKeyDown(Keycode.W)){
Invoke("newVoid", 2); //2 is the time
}
void newVoid()
{
//things you wanna do after 2 seconds...
}
//this delay will happen, when you press W key!
Hope it helps!
Answer by hexagonius · Nov 26, 2016 at 02:25 PM
close enough, it's
yield return new WaitForSeconds(3);
the unity scripting API is a good place to read about how to use functions
The body of PlayerController.NextLevel()' cannot be an iterator block because
void' is not an iterator interface type.
oh whoops, didn't see that. ins$$anonymous$$d of void the method needs to return IEnumerator
Your answer
![](https://koobas.hobune.stream/wayback/20220612101438im_/https://answers.unity.com/themes/thub/images/avi.jpg)