简体   繁体   English

Unity-在游戏中保存进度?

[英]Unity - Save Progress In Game?

Hi I am creating a small game with Unity3d. 嗨,我正在用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. 这样,我可以保存变量,但是仅当我尝试统一时(如果我尝试在Android上不起作用),即可保存该变量。 you know how I can fix? 你知道我该怎么解决吗?

This is how you do it for an example class called MyClass 这是为名为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";
    }
}

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 我已经在我的Web和WebGL构建项目中尝试过此方法,如果您需要了解序列化的知识,我可以举个例子

如果您已添加“ android.permission.WRITE_EXTERNAL_STORAGE”,请检查您对Android项目的权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM