The following is the code I will be using to save character data in my game. I’ve never used this before, or needed to save ingame information at all. So its very new to me.
As I understand it, this is a simple way of saving information, without much fuss, and avoiding saving to player prefs (which I dont want). The Script is added to a game object which is always present no matter what scene(to easily reference) . Im working with 5 scenes, always starting at the same scene.(why I have a “dont destroy” and a singelton(ish) design just in case).
but for the actual save and load code, I don’t know if this will work correctly. I followed a tutorial on saving/loading to unity persistantpath but there were some comments saying that the method is flawed.
Please tell me anything you see as potentially problematic or just wrong. I’m here to learn.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class CharacterInfo : MonoBehaviour
{
public static CharacterInfo character;
public string characterName;
void Awake ()
{
if (character == null)
{
DontDestroyOnLoad(gameObject);
character = this;
}
if (character != this)
{
Destroy(gameObject);
}
}
public void SaveCharacter()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + characterName);
CharacterSaveData saveData = new CharacterSaveData();
//saveData.Stats = This.stats
saveData.hCharacterName = characterName;
bf.Serialize(file, saveData);
file.Close();
}
public void LoadCharacter()
{
if (File.Exists(Application.persistentDataPath + characterName))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + characterName, FileMode.Open);
CharacterSaveData saveData = (CharacterSaveData)bf.Deserialize(file);
file.Close();
//This.stats = saveData.stats
characterName = saveData.hCharacterName;
}
}
}
[Serializable]
class CharacterSaveData
{
public string hCharacterName;
//stats, stuff
}
My main concern is defiantly the SaveCharacter() function. Namely that the file is created, then information is changed. which seems weird to me. shouldnt that line be at the end? or at least after local data is copied to data to be saved?