Unity - Save Progress In Game?

喜夏-厌秋 提交于 2019-12-04 06:32:56

问题


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".



来源:https://stackoverflow.com/questions/29902952/unity-save-progress-in-game

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!