Hello everybody,
I have been struggling with this issue for several days now so I am coming for help. Forgive me if my question might be simple but I am new with coding.
What I want to do is pretty simple. I would like to save all my levels data in a list. For now, I have 2 levels and each level has 3 variables: a string, an int and a bool. Each level is a different scene.
I also would like my game to be able to easily access the information (meaning the 3 variables).
Here is my code
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class CurrentLevelInfo : MonoBehaviour
{
public List <Level> savedLevels = new List<Level>();
public static CurrentLevelInfo levelManager;
// test
string levelName;
void Awake ()
{
LoadLevels ();
// We load the name of the level
levelName = Application.loadedLevelName;
// And we ask the information about the specific level and we get his
switch(levelName)
{
case "Level1":
Level.current = savedLevels[0];
break;
case "Level2":
Level.current = savedLevels[1];
break;
}
}
// Subscribe to event
void OnEnable ()
{
NpcScript.HasFoundConstellation += NewConstellationFound;
}
// Unsubscribe to event
void OnDisable ()
{
NpcScript.HasFoundConstellation -= NewConstellationFound;
}
void NewConstellationFound ()
{
Level.current.hasDiscoveredConstellation = true;
SaveLevels ();
}
public void SaveLevels()
{
BinaryFormatter bf2 = new BinaryFormatter();
FileStream file = File.Create(Application.dataPath + "/savedLevels.dat");
bf2.Serialize(file, savedLevels);
file.Close();
}
public void LoadLevels ()
{
if(File.Exists(Application.persistentDataPath + "/savedLevels.dat"))
{
BinaryFormatter bf2 = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/savedLevels.dat", FileMode.Open);
savedLevels = (List<Level>)bf2.Deserialize(file);
file.Close();
}
}
}
[Serializable]
public class Level
{
public static Level current;
public int neededConstellationsStars;
public string constellationName;
public bool hasDiscoveredConstellation;
}
If you guys could help me. I can read the list info per level but saving and loading don’t seem to work.