Unity游戏障碍物生成间隔异常求助:需实现1秒连续生成
解决障碍物生成间隔不连续的问题
咱们先拆解下你代码里导致停顿的核心原因:你的Spawn()方法里,当两次随机生成的区块索引randomNumber和randomNumber1撞车时,会直接跳过障碍物生成逻辑——这时候协程依然在按1秒间隔跑,但那次循环啥也没生成,就会让玩家感觉像是“停顿”了。另外还有几个小细节可以优化,让生成逻辑更稳定。
具体修复步骤:
1. 确保每次都生成两个不同区块的障碍物
修改Spawn()方法,保证两个随机索引一定不重复,彻底避免空跑的情况:
void Spawn() { // 先选第一个随机区块 int firstIndex = Random.Range(0, spawnPos.Length); // 循环直到选出和第一个不同的索引 int secondIndex; do { secondIndex = Random.Range(0, spawnPos.Length); } while (secondIndex == firstIndex); // 生成两个障碍物 Rigidbody2D clone1 = Instantiate(orginal, spawnPos[firstIndex], Quaternion.identity); Rigidbody2D clone2 = Instantiate(orginal, spawnPos[secondIndex], Quaternion.identity); }
如果想更高效,也可以用集合排除已选索引:
void Spawn() { List<int> availableIndices = new List<int>{0,1,2}; int firstIndex = availableIndices[Random.Range(0, availableIndices.Count)]; availableIndices.Remove(firstIndex); int secondIndex = availableIndices[Random.Range(0, availableIndices.Count)]; Rigidbody2D clone1 = Instantiate(orginal, spawnPos[firstIndex], Quaternion.identity); Rigidbody2D clone2 = Instantiate(orginal, spawnPos[secondIndex], Quaternion.identity); }
2. 优化生成位置的赋值逻辑
你现在在Update()里重复给spawnPos赋值,完全没必要——这些位置是固定的,把赋值移到Start()里就行,省得每一帧做无用功:
void Start() { // 初始化固定生成位置,只做一次 spawnPos[0] = new Vector3(3, 3.86f, -5); spawnPos[1] = new Vector3(-3, 3.86f, -5); spawnPos[2] = new Vector3(0, 3.86f, -5); StartCoroutine(SpawnAtIntervals(1f)); }
3. 调整协程执行顺序(可选)
如果希望游戏启动时立刻生成第一批障碍物,而不是等1秒,可以把Spawn()调用放在yield return之前:
IEnumerator SpawnAtIntervals(float secondsBetweenSpawns) { while (keepSpawning) { // 先生成,再等待,节奏更连贯 Spawn(); yield return new WaitForSeconds(secondsBetweenSpawns); } }
完整修复后的代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class merHinder : MonoBehaviour { public Rigidbody2D orginal; private Vector3[] spawnPos = new Vector3[3]; bool keepSpawning = true; void Start() { // 初始化固定生成位置 spawnPos[0] = new Vector3(3, 3.86f, -5); spawnPos[1] = new Vector3(-3, 3.86f, -5); spawnPos[2] = new Vector3(0, 3.86f, -5); StartCoroutine(SpawnAtIntervals(1f)); } void Update() { // 此处无需再处理spawnPos } private void FixedUpdate() { } void Spawn() { List<int> availableIndices = new List<int>{0,1,2}; int firstIndex = availableIndices[Random.Range(0, availableIndices.Count)]; availableIndices.Remove(firstIndex); int secondIndex = availableIndices[Random.Range(0, availableIndices.Count)]; Rigidbody2D clone1 = Instantiate(orginal, spawnPos[firstIndex], Quaternion.identity); Rigidbody2D clone2 = Instantiate(orginal, spawnPos[secondIndex], Quaternion.identity); } IEnumerator SpawnAtIntervals(float secondsBetweenSpawns) { while (keepSpawning) { Spawn(); yield return new WaitForSeconds(secondsBetweenSpawns); } } }
这样修改后,障碍物就会严格按照1秒间隔连续生成,再也不会出现随机停顿的情况啦。
内容的提问来源于stack exchange,提问作者David Andersson
相关产品推荐
相关产品推荐

