我正在尝试按照 Unity Learn 教程使用协程在游戏中生成立方体,但我做了与教程中相同的所有操作,代码不起作用,并在产量返回新的 WaitForSeconds 后跳过代码。我已经在 stackoverflow 中查看了问题,只有我能找到有同样问题的人,但唯一接受的答案是““可能”在 WaitForSeconds 输入的时间过去之前杀死场景”并且代码是正确的,但有问题场景中。所以,作为一个 Unity 和 C# 新手,我无法解决这个问题。
我在游戏中使用了此代码作为难度按钮;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DifficultyButton : MonoBehaviour
{
private GameManager gameManager;
private Button button;
// Start is called before the first frame update
void Start()
{
button = GetComponent<Button>();
button.onClick.AddListener(SetDifficulty);
gameManager = GameObject.Find("Game Manager").GetComponent<GameManager>();
}
// Update is called once per frame
void Update()
{
}
void SetDifficulty()
{
Debug.Log(gameObject.name + " was clicked");
gameManager.StartGame();
}
}
而这个按钮脚本中使用的GameManager脚本是这样的;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SocialPlatforms.Impl;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.Runtime.CompilerServices;
public class GameManager : MonoBehaviour
{
public List<GameObject> targets = new List<GameObject>(4);
public TextMeshProUGUI scoreText;
public TextMeshProUGUI gameOverText;
public Button restartButton;
public bool isGameActive;
private float score = 0;
private float spawnRate = 1.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
IEnumerator SpawnTarget()
{
Debug.Log("hop ordayım");
Debug.Log("isGameActive: " + isGameActive);
while (isGameActive)
{
Debug.Log("Sonunda burdayım");
yield return new WaitForSeconds(spawnRate);
Debug.Log("Buraya da geldim");
int index = Random.Range(0 ,targets.Count);
Debug.Log("Buraya da");
Instantiate(targets[index]);
Debug.Log("cok sukur be");
}
}
public void UpdateScore(int scoreToAdd)
{
score += scoreToAdd;
scoreText.text = "Score:" + score;
}
public void GameOver()
{
gameOverText.gameObject.SetActive(true);
restartButton.gameObject.SetActive(true);
isGameActive = false;
}
public void RestartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void StartGame()
{
isGameActive = true;
StartCoroutine(SpawnTarget());
Debug.Log("geldim");
UpdateScore(0);
}
}
我使用 Debug.Log 来查看发生了什么,当我单击简单按钮时的输出是这样的;
Easy Button was clicked
hop ordayım
isGameActive: True
Sonunda burdayım
geldim
所以打印“geldim”后它不会继续,尽管我在打印“geldim”后等待超过1秒;
预期产出;
...
geldim
Buraya da geldim
Buraya da
cok sukur be
为什么会发生这种情况?我该怎么办?
在最后添加yield return null