使我的计数器得分保存最高分,即使在应用程序关闭

本文关键字:应用程序 最高分 我的 计数器 保存 | 更新日期: 2023-09-27 18:10:24

所以我正在制作一个火箭应用程序,仍处于早期开发阶段。我写了代码,当我与物体碰撞时,它会计分。如何使它保存我的最高分数,并可以显示它?当我离开我的场景,它设置得分回到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类。PlayerPrefs允许您在游戏会话之间存储数据。

你可以通过调用PlayerPrefs保存数据。设置为任何支持的数据类型(int, float或string),并通过使用相应的PlayerPrefs.Get来获取它。

例如,如果你想保存分数,你可以这样做:

PlayerPrefs.SetInt("score", count);  
PlayerPrefs.Save();

然后通过

取回
count = PlayerPrefs.GetInt("score", 0);