c# - 即使应用程序关闭后,让我的计数器分数保存最高分

标签 c# android unity-game-engine scripting

所以我正在制作一个火箭应用程序,仍处于开发早期。我编写了在与物体碰撞时计算分数的代码。如何制作才能保存我的最高分并可以显示它?我一离开场景,分数就会恢复为 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/

相关文章:

c# - 付款被批准后如何从paypal取回信息?

c# - 抽象类构造器

android-manifest - 仅适用于平板电脑的应用程序

android - 在 Fragment 中哪里发起 View ? onViewCreated 或 onActivityCreated

c - 插件可以在 Linux Unity 编辑器中运行,但不能在独立的 Linux 版本中运行

c# - 如何将枚举与 Vector3 轴一起使用?

c# - 如何在 C# 中使用变量调用对象的属性,例如客户.&fieldName

c# - 延迟执行和急切评估

android - 具有多个条件的 SQL Android 查询公式

unity-game-engine - 从外部源读取电影或更新 Assets