繁体   English   中英

带有延迟的Unity按钮(等待几秒钟)

[英]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.

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