【问题标题】:Set player score with playerprefs使用 playerprefs 设置玩家分数
【发布时间】:2015-10-07 23:59:43
【问题描述】:

我需要保存玩家分数以将其显示为高分,并在每次游戏重新启动或场景重新启动时保留它。我有以下内容:

public class Score : MonoBehaviour {

public static int score = 0;
static int highScore = 0;
public Text text;

public static void AddPoint(){
    score++;
    if (score > highScore) {
        highScore = score;
    }
}

void Start(){
    text = GetComponent<Text> ();
    score = 0;
    highScore = PlayerPrefs.GetInt ("highScore", 0);
}

void onDestroy(){
    PlayerPrefs.SetInt ("highScore", highScore);
}

void Update () {
    text.text = "Score: " + score + "\nHigh Score: " + highScore;
}
}

这会导致我的分数和高分在我每次击中触发器以获得分数时都会增加。但是,然后我使用触发器来判断我是否击中了一个物体以重新启动场景。

void OnCollisionEnter2D(Collision2D col) {
    if (col.gameObject.tag == "Enemy")
    {
        print ("You collided!");
        collided = true;
        rb.gravityScale = 10;
        rb.drag = 0;
        Invoke("startOver", 1.0f);
    }
}

一旦场景重新启动,两个变量 highScore 和 score 都将被重置为零。我猜是因为我的游戏没有保存高分。如何保存分数?

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    在游戏重新开始前添加PlayerPrefs.SetInt

    void OnCollisionEnter2D(Collision2D col) {
        if (col.gameObject.tag == "Enemy")
        {
            print ("You collided!");
            collided = true;
            rb.gravityScale = 10;
            rb.drag = 0;
            PlayerPrefs.SetInt ("highScore", highScore);
            Invoke("startOver", 1.0f);
        }
    }
    

    【讨论】:

    • 这确实有效,但我也发现了为什么它没有保存。我就是这样一个假人。我有 onDestroy() 而不是 OnDestroy()
    猜你喜欢
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多