Unity - 单击重新启动按钮后如何重新启动分数?

时间:2021-04-27 18:13:58

标签: c# unity3d user-interface button scoring

我在正在开发的游戏中遇到了“问题”。当角色因与敌人的碰撞而死亡或触发游戏对象时,它会显示一个游戏结束屏幕,其中包含一个“再试一次”按钮以重新开始游戏,但一旦点击重新开始按钮,从上一场比赛中收集的分数就会保留.

我该如何解决这个问题?谢谢你的帮助!!

GameOver C# 脚本

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");
}

3 个答案:

答案 0 :(得分:1)

由于您有一个静态字段,即使在重置后游戏仍在运行时,这些数据仍将保留。在您的 Reset 函数内放置与此类似的代码。

如果您不想按名称抓取对象,请使用此代码段。

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

您只需在重新加载场景时将分数设置回 0,因为您拥有的值被标记为静态。

答案 1 :(得分:0)

您可以访问 Player 对象(或保存分数的任何对象),然后将变量设置为 0(为此必须公开)。

它会像这样工作: scoreGameObject.getComponent<"ScriptName">().scoreValue = 0

答案 2 :(得分:0)

获取分数类/文件并重置分数

public void RestartButton()
{
    GameObjectWithScoreFile.GetComponent<ScoreClass>().Score = 0; // Make sure the Score var is public 
    SceneManager.LoadScene("Level 1");
    Debug.Log("Game open");
}

如果您因为变量不是静态而出错,只需将其设为静态即可。

示例:

public static int Score = 0;