我是团结的新手,我只是在创造一个简单的星系射击游戏,我希望只有当玩家出现的时候,敌人才会诞生。因此,我已经创建了一个协同线来检查playerExists条件,如果结果是true,它应该继续每5秒进行一次产卵。但出于某种原因,它只产生了一个敌人。我在这里有遗漏什么吗?下面是我的SpawnManager,在那里产卵行为是被控制的。
public class SpawnManager : MonoBehaviour {
[SerializeField]
private GameObject _enemyShipPrefab;
[SerializeField]
private GameObject[] _powerUp;
UIManager _uimanager;
// Use this for initialization
void Start () {
_uimanager = GameObject.Find("Canvas").GetComponent<UIManager>();
StartCoroutine(SpawnPowerUps());
StartCoroutine(SpawnEnemy());
}
IEnumerator SpawnEnemy(){
while (_uimanager.playerExists == true)
{
Vector3 position = new Vector3(Random.Range(-8.23f, 8.23f), 5.7f, 0.0f);
Instantiate(_enemyShipPrefab, position, Quaternion.identity);
yield return new WaitForSeconds(5.0f);
}
}
}下面是我的UIManager,在这里我控制着播放器的存在。
public class UIManager : MonoBehaviour {
// Use this for initialization
public bool playerExists = false;
public int playerScores = 0;
public Sprite[] lives;
public Image playerLivesImagesToBeShown;
public Text playerScoreToBeShown;
public Image titleImage;
public GameObject playerPrefab;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && playerExists == false){
titleImage.gameObject.SetActive(false);
Instantiate(playerPrefab, new Vector3(0, 0, 0), Quaternion.identity);
playerScores = 0;
playerScoreToBeShown.text = "Score : 0";
playerExists = true;
}
}
public void updateLives(int livesToView ){
playerLivesImagesToBeShown.sprite = lives[livesToView];
if(livesToView == 0){
playerExists = false;
titleImage.gameObject.SetActive(true);
}
}发布于 2018-05-16 06:49:59
在第一次看到代码(以及所描述的问题)时,我会说,您的SpawnEnemy()协同器在运行并退出之后。你必须把它锁在某个循环中,就像这样:
IEnumerator SpawnEnemy ()
{
while (true) // Keep checking
{
if(_uimanager.playerExists == true)
{
Vector3 position = new Vector3(Random.Range(-8.23f, 8.23f), 5.7f, 0.0f);
Instantiate(_enemyShipPrefab, position, Quaternion.identity);
yield return new WaitForSeconds (5.0f); // After spawning waits 5secs
}
yield return null; // Starts loop with next frame.
}
}https://stackoverflow.com/questions/50364020
复制相似问题