And*_*rey 2 c# unity-game-engine
我有两个脚本,其中一个重新启动场景,另一个是倒数计时器,而不是在第一个脚本中调用重新启动场景方法。但是,它没有重新启动,即使没有错误,我也不明白为什么。
重启场景的第一个脚本:
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelComplete : MonoBehaviour
{
public void LoadNextLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
public void Exit()
{
Application.Quit();
Debug.Log("Exit");
}
public void Restart()
{
SceneManager.LoadScene(sceneBuildIndex: 1);
Debug.Log("restart pressed");
}
}
Run Code Online (Sandbox Code Playgroud)
倒数计时器结束后应该重新启动场景的第二个脚本:
using UnityEngine;
using UnityEngine.UI;
public class TimerCounDown : MonoBehaviour {
[SerializeField] private Text uiText;
[SerializeField] private float MainTimer;
private float timer;
private string canCount;
private bool doneOnece;
public float restartDelay = 5f;
private string methName;
private void Update()
{
timer -= Time.deltaTime;
Debug.Log((MainTimer - (-timer)));
if ((MainTimer - (-timer)) >0)
{
canCount = (MainTimer - (-timer)).ToString("F1") + " Seconds until end";
uiText.text = canCount;
}
else
{
uiText.text = "level complete lefel will be restarted in 5 seconds";
// GetComponent<LevelComplete>();
// Invoke("Restart", restartDelay);
// GetComponent<LevelComplete>().Restart();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图用Invoke它重新启动它,但它不能GetComponent<LevelComplete>().Restart()作为参数,所以我决定只是简单地触发这个方法,但它不起作用。我不明白为什么以及如何解决它。如果您知道问题出在哪里以及解决方法,请帮助我。
Invoke是属于MonoBehaviour实例的方法。
当您Invoke("Restart", restartDelay);直接调用时,运行时将尝试在TimerCountDown类中找到一个名为“Restart”的方法,因为它是从您调用的地方Invoke开始的,而该方法并不存在。这解释了为什么什么也没有发生。
正确的方法是首先引用LevelComplete实例,然后使用它来调用Invoke:
LevelComplete levelComplete = GetComponent<LevelComplete>();
levelComplete.Invoke("Restart", restartDelay);
Run Code Online (Sandbox Code Playgroud)
这将正确查找类中的“重新启动”方法LevelComplete。