首页 > 解决方案 > 带有延迟的 Unity 按钮(等待几秒钟)

问题描述

我有 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);


 }

}

标签: c#unity3dbutton

解决方案


您不应该启动协程,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。祝你好运!


推荐阅读