简体   繁体   English

Unity - 单击重新启动按钮后如何重新启动乐谱?

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

As you have a static field, this data will persist while the game is still running even after a reset.由于您有一个 static 字段,因此即使在重置后游戏仍在运行时,此数据也会保留。 Inside of your Reset function put code similar to this.在您的Reset function 内部放置与此类似的代码。

If you would rather not grab the object by name, use this snippet.如果您不想按名称获取 object,请使用此代码段。

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.您只需在重新加载场景时将分数设置回 0,因为您拥有的值标记为 static。

You could access the Player Object (or whichever Object holds the score) and simply set the variable to 0 (it has to be public for that).您可以访问播放器 Object(或任何一个 Object 持有分数)并将变量设置为 0(它必须是公开的)。

It would work something like that: scoreGameObject.getComponent<"ScriptName">().scoreValue = 0它会像这样工作: scoreGameObject.getComponent<"ScriptName">().scoreValue = 0

Get the score class/file and reset the score获取分数类/文件并重置分数

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

if you get an error because the variable is not static just make it static.如果因为变量不是 static 而出现错误,只需将其设为 static。

example:例子:

public static int Score = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM