c# - 带有延迟的 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);
}
}
解决方案
您不应该启动协程,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。祝你好运!
推荐阅读
- javascript - 如何检测 React App 中更改的单选按钮
- python - 熊猫处理没有循环的溢出
- blender - Blender 2.93.3 和动画节点插件的恐慌
- java - EJB 托管 bean 父级,在构造函数中带有参数
- spring-boot - 返回列表到控制器 Springboot Thymeleaf
- ios - 未找到 -lFirebaseCore 的 XCode 离子库
- python - 了解匿名函数 lambda 的返回类型
- apache - 使用 Apache httpd 和 AWS ELB 进行 301 重定向
- arrays - 使用 MongoDB 更新文档数组中的多个值的最佳方法是什么?
- python - 当我以管理员身份尝试删除与 Django 应用程序中的另一个对象相关的对象时,如何解决发生的错误?