所以我正在制作一个火箭应用程序,仍处于开发早期。我编写了在与物体碰撞时计算分数的代码。如何制作才能保存我的最高分并可以显示它?我一离开场景,分数就会恢复为 0 :( 请帮忙,谢谢!
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class POINTS1 : MonoBehaviour
{
public Text countText;
public Text winText;
private Rigidbody rb;
private int count;
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText();
winText.text = "";
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pickup"))
{
other.gameObject.SetActive(false);
count = count + 100;
SetCountText();
}
if (other.gameObject.CompareTag("minus300"))
{
other.gameObject.SetActive(false);
count = count -300;
SetCountText();
}
}
void SetCountText()
{
countText.text = "Score: " + count.ToString();
if (count >= 5000)
{
winText.text = "Good Job!";
}
}
}
编辑:所以我尝试了您提供的代码,我做错了什么吗?它不起作用...我想我们可能需要一个 GUI 元素来显示最高分。
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class POINTS1 : MonoBehaviour
{
public Text countText;
public Text winText;
private Rigidbody rb;
private int count;
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText();
winText.text = "";
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pickup"))
{
other.gameObject.SetActive(false);
count = count + 100;
SetCountText();
}
if (other.gameObject.CompareTag("minus300"))
{
other.gameObject.SetActive(false);
count = count -300;
SetCountText();
}
}
void SetCountText()
{
PlayerPrefs.SetInt("score", count);
PlayerPrefs.Save();
count = PlayerPrefs.GetInt("score", 0);
countText.text = "Score: " + count.ToString();
if (count >= 5000)
{
winText.text = "Good Job!";
}
}
}
//PlayerPrefs.SetInt("score", count);
//PlayerPrefs.Save();
//count = PlayerPrefs.GetInt("score", 0);
最佳答案
你想要的是PlayerPrefs类(class)。 PlayerPrefs 允许您在游戏 session 之间存储数据。
您可以通过调用任何支持的数据类型(int、float 或 string)的 PlayerPrefs.Set 来保存数据,并使用相应的 PlayerPrefs.Get 获取数据。
例如,如果你想保存分数,你可以这样做。
PlayerPrefs.SetInt("score", count);
PlayerPrefs.Save();
并在
之前取回它count = PlayerPrefs.GetInt("score", 0);
关于c# - 即使应用程序关闭后,让我的计数器分数保存最高分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32302405/