Unity使用IEnumerator调整InvokeRepeating生成间隔不生效求助
问题原因
你调用InvokeRepeating的时候,传入的spawnSpeed是值传递,Unity会直接把你调用那一刻的数值存下来作为固定调用间隔,后续你修改spawnSpeed变量不会同步到已经启动的InvokeRepeating逻辑里,所以才会出现修改不生效的情况。
解决方案1:全协程实现生成逻辑(更推荐)
直接把障碍物生成逻辑也整合到协程里,每次等待都用最新的spawnSpeed值,代码修改如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObstaclesController : MonoBehaviour { public GameObject obstacle; public Transform ObstacleMarker; private float CloneLifeTime = 4f; float spawnSpeed; float spawnInterval = 3; float minSpawn = -4; float maxSpawn = 0; void Start() { spawnSpeed = 2f; StartCoroutine(SpawnObstaclesContinuously()); StartCoroutine("IncreaseSpeedWithInterval"); } // 新增生成障碍物协程 IEnumerator SpawnObstaclesContinuously() { // 首次生成等待初始间隔 yield return new WaitForSeconds(spawnSpeed); while (true) { AddingObstacle(); // 每次间隔取当前最新的spawnSpeed值 yield return new WaitForSeconds(spawnSpeed); } } IEnumerator IncreaseSpeedWithInterval() { while (true) { yield return new WaitForSeconds(spawnInterval); spawnSpeed *= 1.5f; } } private void AddingObstacle() { float randomLocation = Random.Range(minSpawn, maxSpawn); GameObject obstacleClone = Instantiate(obstacle, ObstacleMarker.position, ObstacleMarker.rotation); obstacleClone.transform.position = new Vector3(ObstacleMarker.transform.position.x, randomLocation, ObstacleMarker.transform.position.z); Destroy(obstacleClone, CloneLifeTime); } }
解决方案2:修改速度时重启InvokeRepeating
如果你不想调整现有结构,也可以每次调整spawnSpeed后先取消原来的Invoke任务,再用新参数重新启动,修改点如下:
void Start() { spawnSpeed = 2f; StartCoroutine("IncreaseSpeedWithInterval"); InvokeRepeating("AddingObstacle", spawnSpeed, spawnSpeed); } IEnumerator IncreaseSpeedWithInterval() { while (true) { yield return new WaitForSeconds(spawnInterval); spawnSpeed *= 1.5f; // 取消旧的Invoke任务 CancelInvoke("AddingObstacle"); // 用新的间隔重新启动 InvokeRepeating("AddingObstacle", spawnSpeed, spawnSpeed); } }
额外提示
你现有逻辑里spawnSpeed *=1.5f会让生成间隔越来越大,障碍物生成越来越慢。如果你需要的是难度提升、生成越来越快的效果,应该改成spawnSpeed /=1.5f,同时可以加个最小间隔阈值,避免生成速度过快影响游戏体验。
内容的提问来源于stack exchange,提问作者Hernaldo Sandoval
相关产品推荐
相关产品推荐

