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

Unity中使用InvokeRepeating时GameObject快速生成问题求助

游戏对象瞬间大量生成问题求助

我正在开发一款游戏,需要从指定位置生成一系列GameObject。我在Start方法中用InvokeRepeating调用生成方法,虽配置了delay和interval参数,但对象仍瞬间大量生成,请求帮助。

我的代码:

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

public class BSpawner : MonoBehaviour
{
    [SerializeField]
    private GameObject[] buildings;

    [SerializeField]
    private float delay=5f;

    [SerializeField]
    private float interval=10f;

    [SerializeField]
    private int destroyDis;
    void Start()
    {
        InvokeRepeating("spawnBuildings", -2000f, -5000f);
    }

    // Update is called once per frame
    void Update()
    {
        spawnBuildings();
    }

    public void spawnBuildings()
    {
        int bIndex = Random.Range(0, buildings.Length);
        Vector2 pos = transform.position;
        Instantiate(buildings[bIndex],pos,Quaternion.identity,this.transform);
    }
}

问题截图:

游戏对象大量生成截图


问题原因及解决方法:

  1. Update方法重复调用生成函数:Update是每帧执行的方法,你在这里直接调用了spawnBuildings(),这会导致每帧都生成一个对象,瞬间就会出现大量实例。直接删掉Update里的spawnBuildings()调用即可。

  2. InvokeRepeating参数错误:你传入的delay和interval是负数,Unity中如果InvokeRepeating的delay为负数,方法会立即执行;interval为负数时,方法会每帧重复执行,这也会导致疯狂生成对象。应该使用你已经序列化的参数,把Start方法里的代码改成:

InvokeRepeating("spawnBuildings", delay, interval);

修改后的完整代码:

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

public class BSpawner : MonoBehaviour
{
    [SerializeField]
    private GameObject[] buildings;

    [SerializeField]
    private float delay=5f;

    [SerializeField]
    private float interval=10f;

    [SerializeField]
    private int destroyDis;
    void Start()
    {
        InvokeRepeating("spawnBuildings", delay, interval);
    }

    public void spawnBuildings()
    {
        int bIndex = Random.Range(0, buildings.Length);
        Vector2 pos = transform.position;
        Instantiate(buildings[bIndex],pos,Quaternion.identity,this.transform);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:58:28