我对Unity和C#非常陌生,并且刚刚开始学习基础知识。我做了一个简单的游戏,有一个立方体向前移动,如果它碰到障碍物,游戏就会重新开始。但是,当我尝试使用Invoke来延迟游戏重新启动后的时间时,当立方体发生冲突时,重新启动是即时的。
我还没能尝试太多,因为我还是C#和Unity的新手。
这是我的GameManager脚本:
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
bool gameHasEnded = false;
public float restartDelay = 3f;
public void EndGame()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("Game Over!");
Invoke("Restart", restartDelay);
Restart();
}
}
void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
当玩家与物体(障碍物脚本)发生碰撞时:
using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
public PlayerMovement movement;
void OnCollisionEnter(Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Obstacle")
{
movement.enabled = false;
FindObjectOfType<GameManager>().EndGame();
}
}
}
我想延迟重启,这样游戏就不会立即重启。任何帮助都将不胜感激:)
发布于 2019-09-22 13:07:17
您在延迟调用Restart
函数之后调用了Restart()
。
// ...
if (gameHasEnded == false) {
gameHasEnded = true;
Debug.Log("Game Over!");
Invoke("Restart", restartDelay);
// This below is called instantly.
// It does not wait for the restartDelay.
Restart();
}
// ...
只需像这样简单地删除Restart()
调用:
if (gameHasEnded == false) {
gameHasEnded = true;
Debug.Log("Game Over!");
Invoke("Restart", restartDelay);
}
请注意,代码不会在Invoke()
处“暂停”。可以将Invoke
看作是异步/协同程序操作。
https://stackoverflow.com/questions/58045858
复制相似问题