问题
Its almost my first time using C sharp and unity. I am trying to use invoke() function in unity but its giving the error
"Trying to Invoke method: EndGame.Restart1 couldn't be called."
public class EndGame : MonoBehaviour
{
bool GameHasEnded = false;
public float Timer = 1f;
public void endgame()
{
if (!GameHasEnded)
{
GameHasEnded = true;
Debug.Log("GameOver");
Invoke("Restart", Timer);
}
void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
}
回答1:
You are trying to
Invoke
a local method that is nested inside of another methodendgame
.Afaik MonoBehaviour.Invoke can only call methods on class level.
It also is either a typo here or in your original code but
Restart1
doesn't exist onlyRestart
. To avoid typos in name based code I would use nameof
Your code should rather look like
public class EndGame : MonoBehaviour
{
private bool GameHasEnded = false;
// Timer is strange name for that
// I would suggest "Delay"
public float Delay = 1f;
public void endgame()
{
if (!GameHasEnded)
{
GameHasEnded = true;
Debug.Log("GameOver");
// In general in order to avoid typos I would prefer to use "nameof"
Invoke(nameof(Restart), Delay);
}
}
private void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
来源:https://stackoverflow.com/questions/65543031/invoke-function-in-unity