0

Hello I'm new in GameDevelopment, and I'm developing a 2D platformer game, the game runs perfectly and even datascript is doing its work but the problem I'm actually facing is if I keep dying while colliding with enemies. for example: if I die 10 times within a minute (i can only die 3 times and gameover menu pops up, I just use the restart level to start the level again). the database resets its health value, manavalue back to 0. I want the mana value and health value to stay in database so that player can upgrade health and mana.

Is there a way to fix it so even I die 100 times within 10 minute database won't crash?[please ignore all those comments i wrote them for my own understandings]

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

}

This my script for saving data. I'm using 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();
    }


}

This is the script for the healthbar slider, and mana bar slider:

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);
    }
}
  • `Application.streamingAssetsPath` is read only. You can't save or delete data from it. You can save data to `Application.persistentDataPath`. Also, if you are going to use `WWW` do that in a coroutine function instead of a `void` function. See the duplicate for how to save, load and delete data. – Programmer Oct 23 '17 at 16:44
  • I'm sorry I'm not finding the link of the dublicate, could you kindly link me? – Nusrat Jahan Shanta Oct 23 '17 at 17:29
  • Refresh this page and you'll see it in your own question under **"This question already has an answer here:"** – Programmer Oct 23 '17 at 17:30
  • Thank you so much, I will use alternative method to save the data like the post suggested. – Nusrat Jahan Shanta Oct 23 '17 at 17:50
  • You're welcome. You can always create new question if you run into issues with that. – Programmer Oct 23 '17 at 17:53

0 Answers0