【发布时间】:2019-05-03 13:51:36
【问题描述】:
我有一个不会自动保存高分的脚本,在我按下重新启动按钮之前,我的高分在没有任何代码的情况下保存了。我希望即使玩家重新开始游戏也能保存高分。这是我的 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
}
}
【问题讨论】:
-
你不需要在 UPDATE 函数中使用 PlayerPrefs.setInt。
-
请注意,您不应该使用玩家偏好来保存游戏数据(例如高分),而是您自己的文件。 PlayerPrefs 适用于播放器的音量、静音状态或首选控制方案等。