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

Unity3D中如何创建循环定时器实现冰块玩家Y轴缩放递减

冰块融化定时器实现方案

方法1:正确使用InvokeRepeating

你之前的问题是误用了Invoke的调用方式——InvokeRepeating可以直接实现每隔指定秒数执行一次函数的需求,不需要在Update里重复调用。示例代码:

public float meltInterval = 2f; // 每2秒触发一次融化
public float scaleReduction = 0.1f; // 每次融化减小的Y轴缩放值

void Start()
{
    // 参数说明:执行的函数名、首次执行延迟、后续执行间隔
    InvokeRepeating(nameof(ReduceIceScale), meltInterval, meltInterval);
}

void ReduceIceScale()
{
    Vector3 currentScale = transform.localScale;
    // 确保缩放不会小于0
    currentScale.y = Mathf.Max(currentScale.y - scaleReduction, 0f);
    transform.localScale = currentScale;

    // 冰块完全融化时停止定时器
    if (currentScale.y <= 0f)
    {
        CancelInvoke(nameof(ReduceIceScale));
        // 这里添加冰块消失的后续逻辑
    }
}

方法2:Update手动计时

如果不想用Unity内置的Invoke方法,可以在Update里手动累计时间,达到间隔后执行逻辑并重置计时:

public float meltInterval = 2f;
public float scaleReduction = 0.1f;
private float timer = 0f;

void Update()
{
    timer += Time.deltaTime;
    if (timer >= meltInterval)
    {
        ReduceIceScale();
        timer = 0f; // 重置计时,开启下一轮
    }
}

void ReduceIceScale()
{
    Vector3 currentScale = transform.localScale;
    currentScale.y = Mathf.Max(currentScale.y - scaleReduction, 0f);
    transform.localScale = currentScale;

    if (currentScale.y <= 0f)
    {
        enabled = false; // 关闭脚本停止计时
        // 添加冰块消失逻辑
    }
}

方法3:协程实现

协程逻辑更直观,适合需要在等待过程中插入额外操作的场景:

public float meltInterval = 2f;
public float scaleReduction = 0.1f;

void Start()
{
    StartCoroutine(MeltIceLoop());
}

IEnumerator MeltIceLoop()
{
    while (transform.localScale.y > 0f)
    {
        yield return new WaitForSeconds(meltInterval);
        ReduceIceScale();
    }
    // 冰块完全融化后的逻辑
}

void ReduceIceScale()
{
    Vector3 currentScale = transform.localScale;
    currentScale.y = Mathf.Max(currentScale.y - scaleReduction, 0f);
    transform.localScale = currentScale;
}

注意:你之前在Update里调用Invoke会导致每帧都注册一个新定时器,这才出现了“持续执行循环”的问题——正确做法是只在初始化时(比如Start方法)调用一次定时器启动逻辑,而非每帧重复调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:51:31