我想在启动时隐藏一个按钮,并在一定时间后使其再次变为活动状态。但是,对WaitForSeconds()
的呼叫无法正常工作。
我尝试了以下操作:
bool
值以跳过WaitForSeconds using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class HideUnhideBtn : MonoBehaviour
{
public Button buttonToHide;
public float comeInTime = 32.5f;
IEnumerator Start()
{
buttonToHide.gameObject.SetActive(false);
yield return new WaitForSeconds(comeInTime);
buttonToHide.gameObject.SetActive(true);
}
}
答案 0 :(得分:4)
到目前为止的答案是不正确的,因为Start()
可以直接用作协程,并且从example in the Manual开始并不需要StartCoroutine
(alas Unity在此功能上不是很明确的开始)。
很可能您将HideUnhideBtn
脚本放在了要禁用的同一GameObject
上。因此,此行buttonToHide.gameObject.SetActive(false);
禁用了脚本中的对象,因此停止了协程。
要解决此问题,您需要使用2个不同的GameObject
。
第二个GameObject
需要在整个时间内保持启用状态。如果禁用它,则将杀死协程。
答案 1 :(得分:0)
您需要使用给定的协程作为参数来调用StartCoroutine
函数,以使其起作用。
例如在这样的启动方法中调用它
StartCoroutine(Start());
答案 2 :(得分:-1)
您必须这样呼叫协程:
public class HideUnhideBtn : MonoBehaviour
{
public Button buttonToHide;
public float comeInTime = 32.5f;
void Start()
{
StartCoroutine(HideAndShowButton());
}
IEnumerator HideAndShowButton()
{
buttonToHide.gameObject.SetActive(false);
yield return new WaitForSeconds(comeInTime);
buttonToHide.gameObject.SetActive(true);
}
}
以下是官方文档:https://docs.unity3d.com/ScriptReference/WaitForSeconds.html
享受!