我有两个脚本,其中一个重新启动场景,另一个是倒计时器,而不是在第一个脚本中调用重新启动场景方法。但是,它没有重新启动,即使没有错误,我也不明白为什么。
重新启动场景的第一个脚本:
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");
}
}
第二个脚本应该在倒计时器结束后重新启动场景:
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();
}
}
}
我正在尝试重新启动它Invoke
但这不能GetComponent<LevelComplete>().Restart()
作为参数,所以我决定简单地触发这个方法,但它不起作用。我不明白为什么以及如何解决它。如果您知道问题出在哪里以及解决方案,请帮助我。
Invoke
是一个属于a的方法MonoBehaviour
实例。
你打电话时Invoke("Restart", restartDelay);
直接地,运行时将尝试在TimerCountDown
类,因为它是你打电话的地方Invoke
来自,不存在。这解释了为什么什么也没有发生。
正确的方法是首先参考LevelComplete
实例,然后使用它来调用Invoke
:
LevelComplete levelComplete = GetComponent<LevelComplete>();
levelComplete.Invoke("Restart", restartDelay);
这将正确地查找“重新启动”方法LevelComplete
class.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)