所以我正在制作一个火箭应用程序,仍处于开发阶段。我编写的代码在与对象碰撞时计算得分。如何使它保存我的最高分并可以显示它?一离开场景,它就会将分数设置为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);
答案 0 :(得分:2)
你想要的是PlayerPrefs课程。 PlayerPrefs允许您在游戏的会话之间存储数据。
您可以通过为任何支持的数据类型(int,float或string)调用 PlayerPrefs.Set 来保存数据,并使用相应的 PlayerPrefs.Get 来获取数据。
例如,如果您想保存分数,可以这样做。
PlayerPrefs.SetInt("score", count);
PlayerPrefs.Save();
通过
取回它count = PlayerPrefs.GetInt("score", 0);