[英]Unity Buttons with Delays (wait for seconds)
我有2個按鈕,即按鈕1和按鈕2,當我單擊按鈕1時,按鈕1從屏幕上移開,按鈕2變為活動狀態。 簡單。 一個簡單的點擊事件。
但是我需要按鈕2,以等待10秒鍾才能在屏幕上激活。
因此,我單擊按鈕1,它會自行移除,然后在10秒鍾內沒有任何反應,然后出現按鈕2。
我想我需要在C#WaitForSeconds中使用,但是我不知道如何使用。
我已經試過了:
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);
}
}
您不應在“ 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);
}
不要忘記將按鈕拖放到公共字段,並且最初不應啟用button2。 祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.