You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中按钮点击后延迟3秒激活面板的协程实现求助

Add 3-Second Delay with Coroutine for Unity Button Panel Activation

Hey there! Let's get that delay working smoothly for your panel activation. The main thing to note is Unity's Button OnClick can only bind to void methods, so we'll have your panelview() method start a coroutine instead of running the logic directly. Here's how to adjust your code:

Full Modified Code

using UnityEngine;
using System.Collections;

public class YourPanelController : MonoBehaviour
{
    public GameObject panel;
    public GameObject panel2;
    public int totalenergy; // Ensure this variable is properly set up in your project

    public void panelview()
    {
        // Trigger the coroutine that handles delay and panel activation
        StartCoroutine(ShowPanelsAfterDelay());
    }

    private IEnumerator ShowPanelsAfterDelay()
    {
        // Wait 3 seconds before executing the activation logic
        yield return new WaitForSeconds(3f);

        // Your original activation logic, refined with else if for better readability
        if (totalenergy == 0)
        {
            panel2.SetActive(true);
        }
        else if (totalenergy >= 1)
        {
            panel.SetActive(true);
        }
    }
}

Breakdown of Key Changes:

  • Coroutine Structure: We created a separate IEnumerator method (ShowPanelsAfterDelay) — this is the required format for Unity coroutines. The yield return new WaitForSeconds(3f); line is what creates the 3-second delay.
  • Button-Compatible Method: Your original panelview() stays as a void method (so the Button can still bind to it). Now it just calls StartCoroutine() to kick off the delayed logic.
  • Logic Clarity: Switched the two standalone if statements to if/else if since totalenergy can't be both 0 and ≥1 at the same time, making the code flow more intuitive.

Quick Validation Checks:

  1. Ensure your script is attached to a GameObject in your scene (since StartCoroutine is a MonoBehaviour method).
  2. Double-check that panel and panel2 are assigned correctly in the Inspector.
  3. If totalenergy might change during the 3-second delay and you need to use its value at the time of the button click, just store it in a local variable before the yield return line.

内容的提问来源于stack exchange,提问作者Chez_jmr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 07:34:06