当一个脚本启用时,在尝试通过游戏模式测试游戏时,团结将卡在"Application.EnterPlayMode“上。阻止它的唯一方法是通过任务管理器()杀死程序。我也看到过类似的问题,其中的问题是脚本中的无限循环。在对我的代码进行三次检查之后,我无法找到任何循环,并担心可能会出现其他问题(下面是正在讨论的脚本)。如果有帮助的话,这个脚本的目标是周期性地生成一个敌人,目前是5秒。如果你知道任何其他原因或在我的脚本中找到一个循环,请让我知道。
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawnerScript : MonoBehaviour
{
public GameObject enemyPrefab;
public int spawnRate = 5;
int timeFromLastSpawn = 0;
// Start is called before the first frame update
void Start()
{
Timer();
}
void Timer ()
{
for (timeFromLastSpawn = 0; timeFromLastSpawn < spawnRate; timeFromLastSpawn++)
{
Thread.Sleep(1000);
}
int randomYPos = new System.Random().Next(0, 5);
SpawnNewEnemy(randomYPos);
Timer();
}
void SpawnNewEnemy(float yPos)
{
Instantiate(enemyPrefab, new Vector2(-12, yPos), Quaternion.identity);
}
}
发布于 2022-08-17 14:16:03
千万不要在Unity (或者大部分的程序,真的)中使用Thread.Sleep
来计时,因为这会暂停整个游戏线程,而不仅仅是一个脚本(您可能认为是这样)。
在这种情况下,您有两个(基本)选项。您可以使用柯鲁丁和WaitForSeconds
// Start is called before the first frame update
void Start()
{
StartCoroutine(Timer());
}
IEnumerator Timer()
{
Random random = new System.Random(); //reuse your random instances
while (spawnEnemies) {
yield new WaitForSeconds(spawnRate); //wait for spawnRate seconds
int randomYPos = random.Next(0, 5);
SpawnNewEnemy(randomYPos);
}
}
或者Update
方法中的计时器变量:
private float spawnRate = 5;
private float timeSinceSpawn;
private Random random = new System.Random(); //reuse your random instances
void Update()
{
timeSinceSpawn += Time.deltaTime;
if (timeSinceSpawn > spawnRate) { //only spawn if we need to
int randomYPos = random.Next(0, 5);
SpawnNewEnemy(randomYPos);
}
}
https://stackoverflow.com/questions/73389915
复制相似问题