Unity - Save Progress In Game?

2019-03-04 00:37发布

问题:

Hi I am creating a small game with Unity3d. But now I have trouble saving some variables. Now I am using the following code

void Awake(){
proiettili  = PlayerPrefs.GetFloat ("PallottoleOgniSecondo");
}

void OnApplicationQuit(){
    PlayerPrefs.SetFloat ("PallottoleOgniSecondo", proiettili);
    PlayerPrefs.Save();
}

This way I can save the variable, but only when I try on unity, if I try does not work on Android. you know how I can fix?

回答1:

This is how you do it for an example class called MyClass

using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

[Serializable]
public class MyClass {

    public int myInt;

    public void Save(){
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create (FilePath());
        bf.Serialize(file, this);
        file.Close();
    }

    public void Load(){
        if(File.Exists(FilePath())){
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(FilePath(), FileMode.Open);
            MyClass loaded = bf.Deserialize(file) as Brochure;
            myInt = loaded.myInt;
        }
    }

    static string FilePath()
    {
        return Application.persistentDataPath + "/myClass.dat";
    }
}


回答2:

You should try it like this

  PlayerPrefs.SetInt("score",ScoreManager.score);
  PlayerPrefs.Save();
  score=PlayerPrefs.GetInt("score");

I've tried this in my project for a Web and WebGL build, if you need to know about serialization I could give you an example



回答3:

Check your permissions of Android project,if you had added "android.permission.WRITE_EXTERNAL_STORAGE".