Unity游戏中Spawn Rate修改后无法在InvokeRepeating中生效求助
问题解决:Unity动态调整Spawn Rate无效的问题
问题原因
InvokeRepeating在调用时会固定重复间隔参数,后续修改spawnRate变量不会影响已经启动的重复调用流程,这就是你看到spawnRate数值变化但生成频率没改变的核心原因。
解决方案1:使用Update手动计时(推荐)
放弃InvokeRepeating,改用Update帧更新控制生成时机,这种方式能直接读取最新的spawnRate值:
private float timer; void Start() { timer = 0.5f; // 初始延迟时间和原有设置一致 } void Update() { timer -= Time.deltaTime; if (timer <= 0) { SpawnPrefab(); timer = spawnRate; // 每次生成后用最新的spawnRate重置计时器 } } // 保留原有SpawnPrefab逻辑,继续修改spawnRate public void SpawnPrefab() { int count = 0; int index = Random.Range(0, 5); int index2 = Random.Range(0, 5); int index3 = Random.Range(0, 5); int index4 = Random.Range(0, 5); int index5 = Random.Range(0, 5); int[] indexler = { index, index2, index3, index4, index5 }; for (int i = 0; i < indexler.Length; i++) { if(indexler[i] == 2 || indexler[i] == 3 || indexler[i] == 4){ count++; } } if(count == 5) { indexler[Random.Range(0, 5)] = Random.Range(0,2); Debug.Log("Count 5 OLDU"); } Vector3 position5 = new Vector3(25f, 5f, zİlk); Instantiate(prefabs[indexler[0]],position5 , prefabs[0].transform.rotation); Vector3 position4 = new Vector3(15f, 5f, zİlk); Instantiate(prefabs[indexler[1]], position4, prefabs[0].transform.rotation); Vector3 position3 = new Vector3(5f, 5f, zİlk); Instantiate(prefabs[indexler[2]], position3, prefabs[0].transform.rotation); Vector3 position2 = new Vector3(-5f, 5f, zİlk); Instantiate(prefabs[indexler[3]], position2, prefabs[0].transform.rotation); Vector3 position1 = new Vector3(-15f, 5f, zİlk); Instantiate(prefabs[indexler[4]], position1, prefabs[0].transform.rotation); spawnRate -= spawnRate * 15 / 100; }
解决方案2:每次生成后重置InvokeRepeating
如果坚持用Invoke系列方法,可以在每次生成后取消原有重复调用,再用新的spawnRate重新启动:
void Start() { Invoke("SpawnPrefab", 0.5f); // 初始只调用一次,不使用InvokeRepeating } public void SpawnPrefab() { // 原有的生成逻辑... spawnRate -= spawnRate * 15 / 100; // 取消之前的重复调用,避免叠加 CancelInvoke("SpawnPrefab"); // 用新的spawnRate启动重复调用 InvokeRepeating("SpawnPrefab", spawnRate, spawnRate); }
注意:不要在Update里调用InvokeRepeating
Update每帧执行一次,重复调用InvokeRepeating会创建大量重叠的重复调用任务,导致生成逻辑混乱,还会引发不必要的性能开销,绝对不能这么做。
内容的提问来源于stack exchange,提问作者Fahrettin Özkan
相关产品推荐
相关产品推荐

