在Unity中检索序列化的Playerprefs特定值

时间:2018-08-10 14:27:16

标签: c# unity3d

我想在我的SaveState类中检索我的整数值,该类已经在Playerprefs中被序列化为字符串,并且我想在PlayerHealth上访问它的值并将其存储在浮动变量。我只是C#的新手,感谢您的理解,希望有人可以对此提供帮助。

这是我的SaveState班:

public class SaveState  {
    public float FullHealth = 10; //The value that i Want
    public float staminaPTS;
}

这是我的PlayerHealth班:

public class PlayerHealth : MonoBehaviour {
    public SaveState stateREF;
    float bulan_fullhp;
    float bulan_fullsp;
    float currHP;
    float currSP;

    //HUD Variables
    public Slider healthSlider;

    void Start () {
        load ();
        bulan_fullhp = // THIS IS WHERE I WANT TO REFERENCE THE SERIALIZED PLAYERPREF "FUllHealth" VALUE IN MY Save_State Class
        currHP = bulan_fullhp;
        currSP = bulan_fullsp;

        //Hud Iniitialization
        healthSlider.maxValue = bulan_fullhp;
        healthSlider.value = bulan_fullhp; 
        Debug.Log (currHP);
    }

    public void save() {
        PlayerPrefs.SetString ("save", Helper.Serialize <SaveState> (stateREF));
    }

    public void load() {
        if (PlayerPrefs.HasKey ("save")) {
            stateREF = Helper.Deserialize<SaveState> (PlayerPrefs.GetString ("save"));
        } else {

            stateREF = new SaveState ();
            save ();
        }
    }

    public void addDamage(float damage) {
        if (damage <= 0)
            return;
        currHP -= damage;
        healthSlider.value = currHP;
        if (currHP <= 0) {
            makeDead ();
        }
    }

    void makeDead() {
        Destroy (gameObject);
    }
}

这是我的Serialization班:

public static class Helper  {

    //Serialze
    public static string Serialize <T> (this T toSerialize) {
        XmlSerializer xml = new XmlSerializer (typeof(T));
        StringWriter writer = new StringWriter ();
        xml.Serialize (writer, toSerialize);
        return writer.ToString ();
    }

    public static T Deserialize<T> (this string toDeserialze) {
        XmlSerializer xml = new XmlSerializer (typeof(T));
        StringReader reader = new StringReader (toDeserialze);
        return (T)xml.Deserialize (reader);
    }
}

2 个答案:

答案 0 :(得分:0)

我很确定我不会理解您的问题,但是会

bulan_fullhp = stateRef.FullHealth;

在这种情况下不完全符合您的要求吗?

答案 1 :(得分:0)

使用XML的过程将相似,但我将使用JSON进行回答。

首先,您将SaveState设置为可序列化

[System.Serializable]
public class SaveState  
{
   public float FullHealth = 10; //The value that i Want
   public float staminaPTS;
}

此时,您可以使用JsonUtility将其转换为JSON:

SaveState ss = new SaveState();
ss.FullHealth = 10f;
ss.staminaPTS = 20f;
string json = JsonUtility.ToJson(ss);
PlayerPrefs.SetString("Save", json);

您要检索的下一个:

string json = PlayerPrefs.GetString("Save", null);
if(string.IsNullOrEmpty(json) == true) { return; } // no saving
SaveState ss = JsonUtility.FromJson<SaveState>(json);
Debug.Log($"{ss.FullHealth} {ss.staminaPTS}");

简单,并且不需要外部库,因为JsonUtility是UnityEngine的一部分。