c# - 如何保存 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
}
}
解决方案
您使用的密钥有问题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);
}
}
推荐阅读
- flask - 错误:saml2.client_base:XML 解析错误:不适合我!!!在使用 haproxy 的 flask_saml 实现中
- azure-iot-edge - 通过边缘运行时模块访问 SMB 文件共享(不带 blob 存储模块)
- ios - Apple 移动产品类型常量,例如“Watch4,4”
- algorithm - Vue.js Dijkstra 算法的性能问题
- javascript - javascript获取网页的最新副本
- javascript - 在新的位置更改时更新地图上的标记位置 - 反应原生
- java - 如何将字符串从适配器传递给 Activity 到 Fragment 然后再传递给 Activity
- css - 网页缓存导致我为不同网页设置的背景图片被清空后才可以替换怎么办?
- html - 导航不显示
- c# - 从c#恢复sql数据库