使用Invoke在另一个脚本上进行Unity调用的方法 [英] Unity calling method on another script using Invoke
问题描述
我有两个脚本,其中一个重新启动场景,另一个是倒计时计时器,而不是在第一个脚本中调用重新启动场景方法.但是,它没有重新启动,即使没有错误,我也不明白为什么.
I have two scripts, one of them restarts the scene and the other is a countdown timer than calls the restart scene method in the first script. However, it's not restarting and I don't understand why even though there are no errors.
第一个重新启动场景的脚本:
The first script that restarts the scene:
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");
}
}
倒数计时器结束后应该重新启动场景的第二个脚本:
The second script that's supposed to restart the scene after a countdown timer ends:
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()
作为参数,因此我决定只触发此方法,但它不起作用.我不明白为什么以及如何解决它.如果您知道问题出在哪里以及解决的方法,请帮助我.
I am trying to restart it with Invoke
but it can't take GetComponent<LevelComplete>().Restart()
as parameter so I decided to just simply fire this method and it doesn't work. I don't understand why and how to fix it. Please help me if you know where the problem is and the solution to it.
推荐答案
Invoke
是属于MonoBehaviour
实例的方法.
直接调用Invoke("Restart", restartDelay);
时,运行时将尝试在TimerCountDown
类中找到一个名为重新启动"的方法,因为该方法是您从中调用Invoke
的位置,而该方法不存在.这解释了为什么什么也没发生.
When you call Invoke("Restart", restartDelay);
directly, the runtime will try and find a method called "Restart" within the TimerCountDown
class since its where you called Invoke
from, which doesn't exist. This explains why nothing happens.
正确的方法是先引用LevelComplete
实例,然后使用该实例来调用Invoke
:
The correct way would be to first reference the LevelComplete
instance and then using that to call Invoke
:
LevelComplete levelComplete = GetComponent<LevelComplete>();
levelComplete.Invoke("Restart", restartDelay);
将在LevelComplete
类中正确查找重新启动"方法.
Which will correctly look for the "Restart" method within the LevelComplete
class.
这篇关于使用Invoke在另一个脚本上进行Unity调用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!