如何用Unity制作“最高得分”

本文是我翻墙看Backeys的How to make a HIGH SCORE in Unity做出的笔记和教程翻译

最高得分适用于很多类型的小游戏,通过UI记录当前得分和最高得分

先在Hierarchy上创建一个panel三个Text和两个button

三个text分别为“Score”“HighScore”“HighScoreTitle”

两个button分别为“RollDiceButton”“ResetButton”

之后创建脚本

using UnityEngine.UI;
using UnityEngine;

public class RollDice : MonoBehaviour{
    public Text Score;
    public Text HighScore;

    void Start()
    {
        HighScore.Text = PlayerPrefs.GetInt("HighScore",0).ToString();
    }
    public void RollDic()
    {
        int number  = Random.Range(1,7);
        Score.text = number.ToString();

        if(number > PlayerPrefs.GetInt("HighScore",0)
        {
            PlayerPrefs.SetInt("HighScore",number);
            HighScore.text = number.ToString();
        }
    }
    public void Reset()
    {
        PlayerPrefs.DeleteAll();
        HighScore.text = "0";
    }

这里要给新手补充一点的是这里应该把挂在脚本的物件直接拖动过去而不是直接拖动脚本

1 static function DeleteAll(): void
 2 描述:从设置文件中移除所有键和值,谨慎的使用它们。
 3 static function DeleteKey(key: string): void
 4 描述:从设置文件中移除key和它对应的值。
 5 static function GetFloat(key: string, defaultValue: float=OF): float
 6 描述:如果存在,返回设置文件中key对应的值.如果不存在,它将返回defaultValue。
 7 static function GetInt(key: string, defaultValue: int): int
 8 描述:返回设置文件中key对应的值,如果存在.如果不存在,它将返回defaultValue。
 9 static function GetString(key: string, defaultValue: string=**): string
10 描述:返回设置文件中key对应的值,如果存在.如果不存在,它将返回defaultValue.
11 static function HasKey(key: string): bool
12 描述:在设置文件如果存在key则返回真.
13 static function SetFloat(key: string, value: float): void
14 描述:设置由key确定的值.
15 static function SetInt(key: string, value: int): void
16 描述:设置由key确定的值.
17 static function SetString(key: string, value: string): void
18 描述:设置由key确定的值.

本次脚本中只用了两个PlayerPrefs

一个是Reset时候使用的Playerprefs.DeleteAll();

另外一个是PlayerPrefs.SetInt();

猜你喜欢

转载自blog.csdn.net/weixin_40833823/article/details/84477423