首页 > 解决方案 > 如何保存 2D 游戏的高分

问题描述

我有一个不会自动保存高分的脚本,在我按下重新启动按钮之前,我的高分被保存而没有任何代码。即使玩家重新开始游戏,我也希望保存高分。这是我的 SCORE 代码:

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

public class Score : MonoBehaviour
{
    public int score;
    public Text ScoreText;
    public int highscore;
    public Text highScoreText;


    void Start()
    {
        highscore = PlayerPrefs.GetInt("HighScore: " + highscore);
    }

    void Update()
    {
        ScoreText.text = "Score: " + score;
        highScoreText.text = highscore.ToString();
        if (score > highscore)
        {
            highscore = score;

            PlayerPrefs.SetInt("HighScore: ", highscore);
        }
    }
    void OnTriggerEnter(Collider other)
    {
        Debug.Log("collider is working");
        if (other.gameObject.tag == "Score: ")
        {
            score++;
        }
    }
}

这是重启按钮的代码:

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class RestartGame : MonoBehaviour
{
    public void RestartsGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name); // loads current scene
    }
}

标签: c#unity3d2d-games

解决方案


您使用的密钥有问题PlayerPrefs

void Start()
{
    highscore = PlayerPrefs.GetInt("HighScore");
}

void Update()
{
    ScoreText.text = "Score: " + score;
    highScoreText.text = highscore.ToString();
    if (score > highscore)
    {
        highscore = score;

        PlayerPrefs.SetInt("HighScore", highscore);

    }
}

推荐阅读