【问题标题】:Unity Buttons with Delays (wait for seconds)带有延迟的 Unity 按钮(等待几秒钟)
【发布时间】:2019-02-12 10:27:57
【问题描述】:

我有 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# unity3d button


    【解决方案1】:

    您不应该在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。祝你好运!

    【讨论】:

    • 阿里你的英雄,非常感谢你
    猜你喜欢
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 2022-01-18
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多