简体   繁体   中英

Unity Buttons with Delays (wait for seconds)

I have 2 buttons, Button 1 & Button 2, When I click Button 1, Button 1 removes from the screen, and button 2 becomes active. easy. a Simple click event.

However I need button 2, to wait 10 seconds before becoming active on the screen.

So I click button 1, it removes itself, then nothing happens for 10 seconds, then button 2 appears.

I think I need to use in C# WaitForSeconds, however I have no idea how.

I have tried this:

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

public class NewBehaviourScript : MonoBehaviour
{

 void Start()
 {
     StartCoroutine(ButtonDelay());
 }

 IEnumerator ButtonDelay()
 {
     print(Time.time);
     yield return new WaitForSeconds(10);
     print(Time.time);


 }

}

You should not start your coroutine in the Start instead start your coroutine when the button clicked by adding a listener to your button like this:

public Button Button1;
public Button Button2;

void Start() {
    // We are adding a listener so our method will be called when button is clicked
    Button1.onClick.AddListener(Button1Clicked);
}  

void Button1Clicked()
{
    //This method will be called when button1 is clicked 
    //Do whatever button 1 does
    Button1.gameObject.SetActive(false);
    StartCoroutine(ButtonDelay());
}

IEnumerator ButtonDelay()
{
    Debug.Log(Time.time);
    yield return new WaitForSeconds(10f);
    Debug.Log(Time.time);

    // This line will be executed after 10 seconds passed
    Button2.gameObject.SetActive(true);
}

Dont forget to drag and drop your buttons to public fields and button2 should not be enabled initially. Good Luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM