Need argent help in Data Serialization..

Hi,

Firstly am a big fan of data Serialization that is (Data Persistence).In my previous games for scores or coins i use serialization, but now am stuck in my new Adventure game, in that i want collect flowers ,each level contains 3 flowers and after collecting it i have to show in level menu each level how many flowers he got.

So here is my all stuff.

Please give me some code that i can achieve .

Here is Level Button script for each level button i attached

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

public class LevelButton : MonoBehaviour {

    public Text levelText;
    public bool unlocked;
    public GameObject star1, star2, star3;

}

Here is my Game Data , except stars thing,

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

[Serializable]
public class GameData {

    private bool isGameStartedFirstTime;


    private bool[] levels;


    public void setIsGameStartedFirstTime(bool isGameStartedFirstTime) {
        this.isGameStartedFirstTime = isGameStartedFirstTime;
    }

    public bool getIsGameStartedFirstTime() {
        return this.isGameStartedFirstTime;
    }

    public void setLevels(bool[] levels) {
        this.levels = levels;
    }

    public bool[] getLevels() {
        return this.levels;
    }


}

Here is my Game Saver

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

public class GameSaver : MonoBehaviour {

    public static GameSaver instance;

    private GameData gameData;

    public bool isGameStartedFirstTime;

    public bool[] levels;

    void Awake()
    {
        InitializeGame ();
        MakeSingleton ();
    }


    void Start ()
    {

        //File.Delete(Application.persistentDataPath + "/GameData.dat");
    }

    void MakeSingleton() {

        if (instance != null) {
            Destroy (gameObject);
        } else {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
    }

    void InitializeGame ()
    {

        if (gameData != null) {
            isGameStartedFirstTime = gameData.getIsGameStartedFirstTime ();
        } else {
            isGameStartedFirstTime = true;
        }

        if (isGameStartedFirstTime) {
            isGameStartedFirstTime = false;

            levels = new bool[3];

            levels[0]=true;
            for (int i = 1; i < levels.Length; i++) {
                levels [i] = false;
            }

            gameData = new GameData();

            gameData.setIsGameStartedFirstTime(isGameStartedFirstTime);

            gameData.setLevels(levels);

            SaveGameData ();
            LoadGameData ();
        }
    }

    void SaveGameData()
    {
        FileStream file = null;

        try {

            BinaryFormatter bf = new BinaryFormatter();

            file = File.Create(Application.persistentDataPath + "/GameData.dat");

            if(gameData != null) {

                gameData.setIsGameStartedFirstTime(isGameStartedFirstTime);

                gameData.setLevels(levels);

                bf.Serialize(file, gameData);

            }

        } catch(Exception e) {

        } finally {
            if(file != null) {
                file.Close();
            }
        }
    }

    void LoadGameData()
    {
        FileStream file = null;

        try {

            BinaryFormatter bf = new BinaryFormatter();

            file = File.Open(Application.persistentDataPath + "/GameData.dat", FileMode.Open);

            gameData = (GameData)bf.Deserialize(file);

            if(gameData !=null)
            {
                levels = gameData.getLevels();
            }
        } catch(Exception e) {

        } finally {
            if(file != null) {
                file.Close();
            }
        }
    }
       

}

For now i dont want lock and unlock system , bcoz i know that , so i want now is in each level how many stars the player get, and save.

Thx.

Seems to me that you can simply have an int[ ] levelStars; right next to your bool array for each level, which would function much the same way. Any particular reason that wouldn’t work?

No I didn’t try that thing . am confuse how to start . so I post in the form .

Some more script would be more helpful . if u can.
The.

Sounds rather strange. If you’ve already achieved that, what exactly prevents you from doing the same for this game?
It’s nothing different.

Fun fact though, these scripts can be found on various websites. Not to mention that it’s doing some stuff in the wrong order.

To be honest, that’s actually not how it works.

Ya i wrap up all the thing what i want , but i didnt fount any thing like star ratings in each level.
Thats y i come up here to take some good suggestions.

I Extended the codes but the problem is , it is not saving the stars…

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

[Serializable]
public class GameData {

    private bool isGameStartedFirstTime;


    private bool[] levels;
    private int[] levelStars;

//    public int maxLevels {
//        get;
//        set;
//    }


    public void setIsGameStartedFirstTime(bool isGameStartedFirstTime) {
        this.isGameStartedFirstTime = isGameStartedFirstTime;
    }

    public bool getIsGameStartedFirstTime() {
        return this.isGameStartedFirstTime;
    }

    public void setLevels(bool[] levels) {
        this.levels = levels;
    }

    public bool[] getLevels() {
        return this.levels;
    }

    public void setLevelStars(int[] levelStars) {
        this.levelStars = levelStars;
    }

    public int[] getLLevelStars() {
        return this.levelStars;
    }
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine.SceneManagement;

public class GameSaver : MonoBehaviour {

    public static GameSaver instance;

    private GameData gameData;

    public bool isGameStartedFirstTime;

    public bool[] levels;
    public int[] levelStars;



    void Awake()
    {
        InitializeGame ();
        MakeSingleton ();
    }


    void Start ()
    {

        //File.Delete(Application.persistentDataPath + "/GameData.dat");


    }

    void MakeSingleton() {

        if (instance != null) {
            Destroy (gameObject);
        } else {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
    }

    void InitializeGame ()
    {

        if (gameData != null) {
            isGameStartedFirstTime = gameData.getIsGameStartedFirstTime ();
        } else {
            isGameStartedFirstTime = true;
        }

        if (isGameStartedFirstTime) {
            isGameStartedFirstTime = false;

            levels = new bool[3];

            levels[0]=true;
            for (int i = 1; i < levels.Length; i++) {
                levels [i] = false;
            }

            levelStars = new int[3];
            for (int i = 0; i < levelStars.Length; i++) {
                levelStars [i] = 0;
            }

            gameData = new GameData();


            gameData.setIsGameStartedFirstTime(isGameStartedFirstTime);
            gameData.setLevels(levels);
            gameData.setLevelStars (levelStars);



            SaveGameData ();
            LoadGameData ();
        }
    }

    public void SaveGameData()
    {
        FileStream file = null;

        try {

            BinaryFormatter bf = new BinaryFormatter();

            file = File.Create(Application.persistentDataPath + "/GameData.dat");

            if(gameData != null) {

                gameData.setIsGameStartedFirstTime(isGameStartedFirstTime);

                gameData.setLevels(levels);
                gameData.setLevelStars (levelStars);



                bf.Serialize(file, gameData);

            }

        } catch(Exception e) {

        } finally {
            if(file != null) {
                file.Close();
            }
        }
    }

    public void LoadGameData()
    {
        FileStream file = null;

        try {

            BinaryFormatter bf = new BinaryFormatter();

            file = File.Open(Application.persistentDataPath + "/GameData.dat", FileMode.Open);

            gameData = (GameData)bf.Deserialize(file);

            if(gameData !=null)
            {
                levels = gameData.getLevels();
                levelStars = gameData.getLLevelStars();

            }
        } catch(Exception e) {

        } finally {
            if(file != null) {
                file.Close();
            }
        }
    }
       

    public void SetStars(int levelNumber, int stars)
    {
        levelStars[levelNumber] = stars;
    }

    public int GetStars(int levelNumber)
    {
        return levelStars[levelNumber];
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour {

    public int currentLevel;
    public int levelAmount=5;

    public int totalStars;

    private bool[] levels;
    private int[] levelStars;


    void Awake()
    {
       

    }

    void Start ()
    {
        levels = GameSaver.instance.levels;
        levelStars = GameSaver.instance.levelStars;

        CheckCurrentLevel ();


        totalStars = GameSaver.instance.GetStars (currentLevel);

    }
   

    void Update ()
    {
        if (Input.GetMouseButtonDown (0)) {
            totalStars++;


            GameSaver.instance.SetStars(currentLevel, totalStars);


        }
       
    }

//    public void SaveNextLevel()
//    {
//        int nextLevel = currentLevel + 1;
//
//        if (nextLevel < GameSaver.instance.levels.Length)
//        {
//            for (int i = 1; i < GameSaver.instance.levels.Length; i++) {
//                if(GameSaver.instance.levels[i]){
//                    GameSaver.instance.levels[i + 1] = true;
//                }
//            }
//
//
//        }
//    }

    public void CheckCurrentLevel()
    {
        for (int i = 1; i < levelAmount; i++)
        {
            if(SceneManager.GetActiveScene().name=="Level"+i) {
                currentLevel = i;
            }
        }
    }
}

That’s simply due to logical errors.
When you call Initialize() on your ‘GameSaver’ you do the following:

At this time, gameData will always be null as it has neither been initialized nor loaded. ‘isGameStartedFirstTime’ will then always be set to true, which in turn means, that the code in the subsequent if statement will always be executed.
It then creates the initial gameData, saves it (no matter what is saved, it’d be replaced) and reloads it.

So you actually want to load it before you do anything else.

Other than that, the singleton instance check should run first, the initialization afterwards, but only if the instance is a valid one, i.e. it’s the actual singleton.
And the the array of per-level-data should become its own type. Several synced arrays may not cause problems if properly encapsulated/used, but it’s usually a bad approach to keep track of data in such a loosely manner if it belongs together.

I can really understand that you want to extend existing code that can be found on the internet, but it often does not make alot of sense if you do not fully understand what’s happening there.

Thx i ll check the sequence, i dont have enough knowledge about coding part…

if Then, how do i initialize the gata and where i have to??

You’d do it at the beginning of the InitializeGame() method. Just try to load the data. In order to not cause unnecessary exceptions, you should also check whether the file exists or not. If it doesn’t, you’ll create it with the initial values (which your save method apparently does at the moment).

Thx dude , ya i actually forget that , but when i check my previous games i load first and then initializa the data ,

Thx a lot…