You need to enable JavaScript to run this app. Unity跨场景停留后进入游戏即批量生成敌人的问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

Unity跨场景停留后进入游戏即批量生成敌人的问题咨询

问题根因

你碰到的批量生成问题,核心是时间基准用错了:

  • 代码里用的Time.time是从整个游戏进程启动开始累计的全局运行时长,不会因为场景切换自动重置
  • 当你在主菜单/商店停留20秒后进入关卡时,全局Time.time的值已经累计到20左右
  • 你在初始化阶段把nextActionTime设为0,导致进入关卡后的连续几十毫秒内的多次Update调用,每次都会触发生成逻辑(因为20s的全局时间始终大于 0+1s、1+1s...直到19+1s的nextActionTime值),短时间内连续刷出20个敌人,视觉上就表现为“一次性生成全部敌人”
  • 这也是你把初始化逻辑从Start改到Awake完全没用的原因——只要用全局Time.time做对比基准,场景切换时带过来的时长差就一定会触发批量生成
修复方案

把全局时间基准换成场景独立的计时接口,直接用Unity提供的Time.timeSinceLevelLoad即可,这个值会在每次场景加载完成时自动重置为0,完全匹配你要的逐秒生成节奏。
同时可以顺手清理代码里的冗余逻辑、把硬编码的数组随机范围改成动态获取,避免后续调整配置时出现数组越界问题。

修复后的完整脚本如下:

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

public class SpawnScript : MonoBehaviour
{
    public Transform[] spawnPoints;
    public GameObject[] enemyPrefabs;
    private float nextActionTime;
    private readonly float period = 1f;

    void Start()
    {
        // 直接以关卡加载完成的时间作为计时起点
        nextActionTime = Time.timeSinceLevelLoad;
    }

    void Update()
    {
        if (Player.isDead) return;
        
        // 用场景独立时间做对比,不会带上菜单/商店的停留时长
        if (Time.timeSinceLevelLoad > nextActionTime)
        {
            nextActionTime += period;
            // 随机范围跟随数组实际长度,避免硬编码导致越界
            int spawnArrayKey = Random.Range(0, spawnPoints.Length);
            int enemyId = Random.Range(0, enemyPrefabs.Length);
            Instantiate(
                enemyPrefabs[enemyId], 
                spawnPoints[spawnArrayKey].position, 
                spawnPoints[spawnArrayKey].rotation
            );
        }
    }
}

可选优化方案

如果想要更稳定的生成节奏,不受帧率波动影响,可以把Update轮询换成协程实现:

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

IEnumerator SpawnEnemyLoop()
{
    // 循环直到玩家死亡,每隔1秒生成一个敌人
    while (!Player.isDead)
    {
        yield return new WaitForSeconds(period);
        int spawnArrayKey = Random.Range(0, spawnPoints.Length);
        int enemyId = Random.Range(0, enemyPrefabs.Length);
        Instantiate(
            enemyPrefabs[enemyId], 
            spawnPoints[spawnArrayKey].position, 
            spawnPoints[spawnArrayKey].rotation
        );
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 07:15:03