用playerprefs设置玩家得分

时间:2015-07-18 09:36:11

标签: unity3d

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

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都将重置为零。我猜是因为我的游戏没有保存highScore。如何保存分数?

1 个答案:

答案 0 :(得分:0)

在游戏重启之前添加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);
    }
}