Unity - Save Progress In Game?

2019-03-04 00:31发布

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?

3条回答
够拽才男人
2楼-- · 2019-03-04 00:58

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";
    }
}
查看更多
再贱就再见
3楼-- · 2019-03-04 00:59

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

查看更多
可以哭但决不认输i
4楼-- · 2019-03-04 01:18

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

查看更多
登录 后发表回答