Hello I’ve been working on a save/load system for my RPG inventory, and I was wondering whether there was a way to make the script use Serialization instead of PlayerPrefs, because I want the player to be able to access their save file. The main issue I run into with this code is how it mixes up the same variable in different itemHolders, causing duplication. Also, I heard that PlayerPrefs is better used for settings or preferences. Here’s my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class ItemInformation : MonoBehaviour
{
// These are the assets for the item to change
public Text nameText;
public Text descriptionText;
public Text regenText;
public Text amountText;
// This is the identifier for each item
public string identifier;
// These are the variables that change with the different items
public string itemName;
public string itemDescription;
public float itemRegeneration;
public int itemAmount;
// Starts on awake
void Awake()
{
// Function to change the object's information and such
nameText.text = itemName;
descriptionText.text = itemDescription;
regenText.text = "HEALS " + itemRegeneration + "HP";
// Loads game data
LoadDataIfNeeded();
}
void Update()
{
amountText.text = "HAVE:" + itemAmount;
}
private void SaveData()
{
string jsonString = JsonUtility.ToJson(this);
PlayerPrefs.SetString(identifier, jsonString);
// Creates file to store variables
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/InvData.dat");
SaveData data = new SaveData();
// Gets the player data
data.itemSave = myItemAmount.itemAmount;
// Writes player data to file and encrypts it
bf.Serialize(file, data);
file.Close();
}
public void LoadDataIfNeeded()
{
if (PlayerPrefs.HasKey(identifier))
{
string jsonInstance = PlayerPrefs.GetString(identifier);
JsonUtility.FromJsonOverwrite(jsonInstance, this);
// Extracts the data from the binary file and reads it
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/InvData.dat", FileMode.Open);
SaveData data = (SaveData)bf.Deserialize(file);
file.Close();
myItemAmount.itemAmount = data.itemSave;
}
else
{
SaveData();
}
}
}
// Holds data that is to be saved
[Serializable]
class SaveData
{
// Variables for save file
public int itemSave;
}
[System.Serializable]container for your save data, and using one of the available serialization libraries to convert it into a text or binary file to write to disc withSystem.IO? Where specifically did you run into trouble that we can help you solve? \$\endgroup\$Application.persistentDataPath, yes? \$\endgroup\$