在我按下重新启动按钮后,游戏会重新启动,但不会产生目标 当我第一次启动游戏时它可以工作,但重新启动后它不会生成目标,光标也应该消失并将其变成十字继承人。它尝试了很多东西,但它不起作用
public int totalHits = 0;
public int ballHit = 0;
public Image accuracyImage;
public TextMeshProUGUI countDownText;
public TextMeshProUGUI scoreText;
public TextMeshProUGUI performanceText;
public TextMeshProUGUI ballHitText;
public TextMeshProUGUI percentageText;
public float countDown;
public float accuracy = 0f;
public float accuracyFA = 0f;
public bool isGameOver = false;
public FirstPersonController fpsScript;
void Awake()
{
isGameOver = false;
countDown = 120;
StartCoroutine(Spawner());
//InvokeRepeating("Spawner", 1, 1);
}
// Update is called once per frame
void Update()
{
accuracy = ballHit * 100 / totalHits;
if (countDown > 0)
countDown -= Time.deltaTime;
countDownText.text = (countDown).ToString("0");
scoreText.text = accuracy + "%";
if (countDown < 1)
{
isGameOver = true;
}
if (isGameOver)
{
GameOver();
}
accuracyFA = ballHit / totalHits;
//Spawner();
}
IEnumerator Spawner()
{
while (true)
{
yield return new WaitForSeconds(0.5f);
if (countDown > 0 && noOfBalls <= 3)
{
Vector3 position = new Vector3(Random.Range(-270, 230), Random.Range(20, 180), 355);
Instantiate(target, position, target.transform.rotation);
Debug.Log("Spawned");
noOfBalls++;
}
}
}
void GameOver()
{
Time.timeScale = 0f;
fpsScript.RotationSpeed = 0f;
gameOverMenu.SetActive(true);
accuracyImage.fillAmount = accuracyFA / 10;
ballHitText.text = (ballHit).ToString("0");
percentageText.text = accuracy + "%";
HUD.SetActive(false);
if(ballHit <= 40)
{
performanceText.text = "Poor, Need Practice";
}
else if(ballHit <= 70)
{
performanceText.text = "Good, Can Improve";
}
else if(ballHit >= 70)
{
performanceText.text = "Well Done, Keep It Up";
}
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
crossheir.SetActive(false);
}
public void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
目标应该产生,光标应该消失并变成十字继承人
对于初学者来说,在您的生成器协程中,您有一个带有
While(true)
语句的无限循环。您需要添加一种方法使其变为 false,以便可以退出 while 循环。在 if 语句末尾添加 else 子句可能有助于做到这一点。
while (true)
{
yield return new WaitForSeconds(0.5f);
if (countDown > 0 && noOfBalls <= 3)
{
//Code here
}
else
{
break;
}
}
您似乎也没有使用代码顶部的其余变量创建变量 noOfBalls 。我假设它是在其他地方创建的,因为它会抛出错误代码,但请确保它存在,因为这可能是您没有意识到的问题。重新启动场景后,您也不要将 noOfBalls 变量重新设置为 0(或低于 3 的另一个基值)。这意味着当它调用新的生成器协程时,if 语句已经得到满足。类似于下面的代码片段的内容可能会帮助您解决问题。
private int noOfBalls = 0;
void Awake()
{
noOfBalls = 0;
isGameOver = false;
countDown = 120;
StartCoroutine(Spawner());
//InvokeRepeating("Spawner", 1, 1);
}
同时,鼠标没有返回到十字准线的原因是因为在
GameOver()
方法中你出现了鼠标,但从未调用你用来让它成为十字准线的方法。所以它不知道自己需要成为十字准线。在唤醒方法期间调用它可能是一个好主意,以确保它始终在启动场景时生成。