Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

c# - Unity - How can I restart the score once the restart button is clicked?

I am having a "problem" in a game that is being developed. When the character dies from a collision to the enemy, or trigger gameobjects, it displays a game over screen, which contains a "Try Again" button to restart the game, but the score collected from the previous game remains once the restart button is clicked.

How can I solve this problem? Thank you for your help!!

GameOver C# script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class CS_GameOverMenu : MonoBehaviour
{

    

    public void RestartButton()
    {
        SceneManager.LoadScene("Level 1");
        Debug.Log("Game open");

    }

    public void MenuButton()
    {

        SceneManager.LoadScene("MainMenu");
        Debug.Log("Main Menu open");
    }

    public void ExitButton()
    {
        Application.Quit();
        Debug.Log("Game closed");

    }

    //public void QuitButton()
    //{
    //  Application.Quit();
    //Debug.Log("Game closed");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As you have a static field, this data will persist while the game is still running even after a reset. Inside of your Reset function put code similar to this.

If you would rather not grab the object by name, use this snippet.

public void RestartButton()
{
    ScoringSystem.theScore = 0;
    SceneManager.LoadScene("Level 1");
    Debug.Log("Game open");
}

You just need to set the score back to 0 when reloading the scene as the value you have is marked as static.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...