I've been working on an RPG videogame, and I have been trying to implement a Save button into my game, which is supposed to save the player's itemAmount variable, which is in another script, called ItemInformation. I retrieve the itemAmount variable at Start() by getting the script from the itemHolder GameObject. I plan to use this script in multiple GameObjects, because I use the same variable (itemAmount) with different values in different GameObjects. For some reason, I don't receive any errors or warnings in the Console. Here is my script to the Saving System:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class InventorySave : MonoBehaviour
{
// Public variables for inventory and health
private GameObject itemHolder;
private ItemInformation myItemAmount;
// Initiates before the first frame
void Start()
{
// Gets components for the player variables
itemHolder = transform.gameObject;
myItemAmount = itemHolder.GetComponent<ItemInformation>();
}
// Function that will be called when player saves game from pause menu
public void SaveGame()
{
// Creates file to store variables
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/SaveData.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();
}
}
// Holds data that is to be saved
[Serializable]
class SaveData
{
// Variables for save file
public int itemSave;
}