gpt4 book ai didi

c# - 使用 Invoke 在另一个脚本上调用 Unity 方法

转载 作者:行者123 更新时间:2023-12-05 01:17:27 24 4
gpt4 key购买 nike

我有两个脚本,其中一个重新启动场景,另一个是倒数计时器,而不是在第一个脚本中调用重新启动场景方法。但是,它没有重新启动,即使没有错误,我也不明白为什么。

第一个重启场景的脚本:

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 是属于 MonoBehaviour 实例的方法。

当您直接调用 Invoke("Restart", restartDelay); 时,运行时将尝试在 TimerCountDown 类中找到一个名为“Restart”的方法,因为它的位置您调用了 Invoke ,但它并不存在。这就解释了为什么什么都没发生。

正确的方法是首先引用 LevelComplete 实例,然后使用它来调用 Invoke:

LevelComplete levelComplete = GetComponent<LevelComplete>();
levelComplete.Invoke("Restart", restartDelay);

这将在 LevelComplete 类中正确查找“Restart”方法。

关于c# - 使用 Invoke 在另一个脚本上调用 Unity 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50313321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com