首页 > 解决方案 > 如何在 Unity 中保存和加载文本的值?

问题描述

我有一个代码,其中有一个体验栏,下面是一个级别文本框和一个体验文本框。这是代码:

    public Slider barraExperiencia;
    public Button botonManzana;
    public Text txtNumeroNivel, txtNumeroExperiencia;

    void Start()
    {
        barraExperiencia.value = PlayerPrefs.GetFloat("Experiencia");
        nivel = PlayerPrefs.GetFloat("Nivel");

        botonManzana.onClick.AddListener(ButtonAlimentoClicked);

    }

    void Update()
    {
        PlayerPrefs.SetFloat("Experiencia", barraExperiencia.value);
        PlayerPrefs.SetFloat("Nivel", nivel);
        txtNumeroExperiencia.text = barraExperiencia.value.ToString() + "/" + barraExperiencia.maxValue.ToString();

        if (barraExperiencia.value >= barraExperiencia.maxValue)
        {
            barraExperiencia.value = 0;
            nivel += 1;
            txtNumeroNivel.text = nivel.ToString();
            barraExperiencia.maxValue += 100;
        }

    }

    void ButtonAlimentoClicked()
    {
       barraExperiencia.value += 10;
    }

在代码中,当按下按钮 botonManzana 时,它会增加条形的值。当 bar 的值达到最大值时,它返回 0,变量 nivel(级别)增加。

我想保存并加载 bar 和“nivel”的值,我已经使用 PlayerPrefs 完成了它,就像代码中显示的那样,但它不起作用。如果有人可以帮助我,请。

标签: c#user-interfaceunity3dsaveload

解决方案


您需要调用 Save() 以将更改保存在 PlayerPrefs 上。请参阅https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

如果 OnApplicationQuit 没有被调用,它可能不会被自动调用,例如,如果您的应用程序是 WebGL 应用程序。有关详细信息,请参阅https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationQuit.html


推荐阅读