Unity3d:保存在数据库脚本中的值重置。

时间:2017-10-23 15:59:12

标签: c# unity3d binaryformatter

你好我是GameDevelopment的新手,我正在开发一款2D平台游戏,游戏运行完美,甚至数据脚本正在开展工作,但我实际面临的问题是如果我在与敌人发生碰撞时继续死亡。例如:如果我在一分钟内死了10次(我只能死3次并弹出游戏菜单,我只需使用重启级别再次启动级别)。数据库重置其健康值,manavalue回到0.我希望法术力值和健康值保留在数据库中,以便玩家可以升级生命值和法力值。

有没有办法解决它,所以即使我在10分钟内死了100次数据库也不会崩溃?[请忽略我为他自己的理解写下的所有评论]

using System.Collections;
using System.Collections.Generic;
using System;  // give access to the [Serializable] Attribute


/// <summary>
/// the GameData for your Model.
/// </summary>

[Serializable]// this attribute allows to save data inside this class


public class GameData
{
    public int coinCount;//for tracking the coin
    public int score; //for tracking the score
    public int lives; //for tracking the player lives
    public int totalScore;//for tracking the total score of all levels
    public float playerHealth;
    public float playerMana;
    public bool[] keyFound; //for tracking which keys have been found
    public bool[] skinUnlocked;//to track which skins are unlocked
    public bool[] selectedSkin;//to track which skin user will play  with
    public bool[] projectileUnlocked;//to track which projectiles are unlocked

    //for checkpoints
    public bool[] checkPoint;
    public int savedScore, savedCoinCount;
    public bool canfire;
    //public bool isFirstBoot; // for initializing when the game starts for the first time
    public LevelData[] leveldata; //for tracking level data like level unlocked, stars awarded, level number


    public bool playSound;  //for toggleMusic
    public bool playMusic; // for toggle Music
    public bool firstBoot;// for initializing when the game starts for the first time

}

这是我保存数据的脚本。我正在使用BinaryFormatters():

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



public class DataController : MonoBehaviour {

    public static DataController instance = null;
    public GameData data;
    public bool devMode; //to help "sync" data between editor and mobile

    string dataFilePath;            //path where file is stored
    BinaryFormatter bf;             //helps save/load data in binary files

    void Awake () {
        //code to make a singleton
        if (instance == null){
            instance = this;
            DontDestroyOnLoad(gameObject);

        }
        else{
            Destroy(gameObject);
        }

        bf = new BinaryFormatter();
        dataFilePath = Application.persistentDataPath + "/game.dat";
        //Debug.Log(dataFilePath);
    }


    public void RefreshData(){

        if (File.Exists(dataFilePath)){
            FileStream fs = new FileStream(dataFilePath, FileMode.Open);//preparing the game.dat file to edit
            data = (GameData)bf.Deserialize(fs); //bringing the contents from the database file in object format
            fs.Close();
        }
    }
    public void SaveData(){
        FileStream fs = new FileStream(dataFilePath, FileMode.Create);
        bf.Serialize(fs, data);
        fs.Close();
    }

    public void SaveData(GameData data)
    {
        FileStream fs = new FileStream(dataFilePath, FileMode.Create);
        bf.Serialize(fs, data);
        fs.Close();
    }
    public  bool IsUnlocked(int levelNumber){
        return data.leveldata[levelNumber].isUnlocked;

    }


    public int GetStars(int levelNumber){
        return data.leveldata[levelNumber].starsAwarded;
    }


    void OnEnable(){
        CheckDB();
    }

    void CheckDB(){
        if (!File.Exists(dataFilePath))
        {
            //platform depended compilation
            #if UNITY_ANDROID
            CopyDB();
            #endif
        }
        else{

            if (SystemInfo.deviceType == DeviceType.Desktop)
            {
                string destFile = System.IO.Path.Combine(Application.streamingAssetsPath, "game.dat");
                File.Delete(destFile);
                File.Copy(dataFilePath, destFile);
            }

            if (devMode){
                if (SystemInfo.deviceType == DeviceType.Handheld){
                    File.Delete(dataFilePath);
                    CopyDB();
                }
            }
            RefreshData();
        }
    }

    void CopyDB(){
        string srcFile = System.IO.Path.Combine(Application.streamingAssetsPath, "game.dat");
        //retrieve db file from apk
        WWW downloader = new WWW(srcFile);
        while (!downloader.isDone)
        {

            //nothing to be done while our db gets our db file
        }

        //then save file to Apllication.persistentdataPath
        File.WriteAllBytes(dataFilePath, downloader.bytes);
        RefreshData();
    }


}

这是健康栏滑块和法术力栏滑块的脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class HealthAndManaBar : MonoBehaviour
{

    public Image HealthBar;
    public Image ManaBar;
    public RectTransform manabutton;
    public RectTransform healthbutton;
    // Use this for initialization

    public float healthValue;
    public float manaValue;
    void Start()
    {

        healthValue = GameController.instance.data.playerHealth;
        manaValue = GameController.instance.data.playerMana;
        HealthChange(healthValue);
        ManaChange(manaValue);

    }

    // Update is called once per frame
    void Update()
    {
        if (manaValue < GameController.instance.data.playerMana)
        {
            manaValue += Time.deltaTime * 20;
            ManaChange(manaValue);
        }

        if (healthValue < 0)
        {
            healthValue = 0;
            HealthChange(healthValue);
        }
    }

    public void HealthChange(float healthValue)
    {
        float amount = (healthValue / GameController.instance.data.playerHealth) * 180.0f / 360;
        HealthBar.fillAmount = amount;
        float buttonAngle = amount * 360;
        healthbutton.localEulerAngles = new Vector3(0, 0, -buttonAngle);
    }

    public void ManaChange(float manaValue)
    {
        float amount = (manaValue / GameController.instance.data.playerMana) * 180.0f / 360;
        ManaBar.fillAmount = amount;
        float buttonAngle = amount * 360;
        manabutton.localEulerAngles = new Vector3(0, 0, -buttonAngle);
    }
}

0 个答案:

没有答案