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

Unity教程二次实践问题:InvokeRepeating无限生成对象

问题原因与解决方法

核心问题

你把InvokeRepeating("SpawnObstacle", startDelay, repeatRate)放在了Update()方法里。Update()是Unity每帧都会执行的方法,这意味着每帧都会新增一个重复生成对象的任务——相当于同时启动了几百个“延迟2秒后每隔2秒生成一个对象”的进程,所以会瞬间生成大量对象,调整repeatRate数值当然不会有明显变化。

解决步骤

把InvokeRepeating的调用移到Start()方法里即可。Start()只会在脚本首次加载时执行一次,这样只会注册一个重复生成任务,就能实现预期的延迟生成效果。

修改后的完整代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnManager : MonoBehaviour
{
    public GameObject obstaclePrefab;
    private Vector3 spawnPOS = new Vector3(25, 0, 0);
    private float startDelay = 2;
    private float repeatRate = 2;
    

    // Start is called before the first frame update
    void Start()
    {
        InvokeRepeating("SpawnObstacle", startDelay, repeatRate);
    }

    // Update is called once per frame
    void Update()
    {
        // 此处无需保留InvokeRepeating调用
    }

    void SpawnObstacle()
    {
        Instantiate(obstaclePrefab, spawnPOS, obstaclePrefab.transform.rotation);
    }
}

内容的提问来源于stack exchange,提问作者Sims Studios LLC

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:25:17