[英]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. 我有2个按钮,即按钮1和按钮2,当我单击按钮1时,按钮1从屏幕上移开,按钮2变为活动状态。 easy.
简单。 a Simple click event.
一个简单的点击事件。
However I need button 2, to wait 10 seconds before becoming active on the screen. 但是我需要按钮2,以等待10秒钟才能在屏幕上激活。
So I click button 1, it removes itself, then nothing happens for 10 seconds, then button 2 appears. 因此,我单击按钮1,它会自行移除,然后在10秒钟内没有任何反应,然后出现按钮2。
I think I need to use in C# WaitForSeconds, however I have no idea how. 我想我需要在C#WaitForSeconds中使用,但是我不知道如何使用。
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: 您不应在“
Start
启动协程,而应在单击按钮时通过向按钮添加侦听器来启动协程,如下所示:
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. 不要忘记将按钮拖放到公共字段,并且最初不应启用button2。 Good Luck!
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.