I’m totally new to Unity and please help me figure out how to save & load items that are currently held in the inventory. Basically, I’m trying to serialize & save my game state to a binaryformat file. I know how to save/load variables like int, string, etc., but the inventory has an array w/ images and, after spending a couple of days on this issue, I’m still not quite sure how I should go about this, in fact I’m totally lost. Here are my scripts & any advice would be greatly appreciated. Thanks!
Item script:
using UnityEngine;
[CreateAssetMenu]
public class Item : ScriptableObject
{
public int itemID;
public string itemName;
public Sprite itemSprite;
}
Inventory script to add & remove items to/from the inventory:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Inventory : MonoBehaviour {
public static Inventory inventoryS;
public const int numSlots = 7;
public Image[] itemImages = new Image[numSlots];
public Text[] itemNames = new Text[numSlots];
public Item[] items = new Item[numSlots];
public void AddItem(Item itemToAdd){
for (int i = 0; i < items.Length; i++) {
if (items[i] == null) {
items[i] = itemToAdd;
itemImages[i].sprite = itemToAdd.itemSprite;
itemNames[i].text = itemToAdd.itemName;
itemImages[i].enabled = true;
return;
}
}
}
public void RemoveItem(Item itemToRemove){
for (int i = 0; i < items.Length; i++) {
if (items[i] == itemToRemove) {
items[i] = null;
itemImages[i].sprite = null;
itemNames [i].text = null;
itemImages[i].enabled = false;
return;
}
}
}
}
GameManager script to save & load the game state (persistent throughout the game):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using UnityEngine.SceneManagement;
public class GameControl : MonoBehaviour {
public static GameControl control;
public float health;
void Awake(){
if (control == null) {
DontDestroyOnLoad (gameObject);
control = this;
} else if (control != this) {
Destroy (gameObject);
}
}
public void Save(){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create (Application.persistentDataPath + "/playerInfo.dat");
PlayerData data = new PlayerData ();
data.health = health;
bf.Serialize (file, data);
file.Close ();
}
public void Load(){
if (File.Exists (Application.persistentDataPath + "/playerInfo.dat")) {
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize (file);
file.Close ();
health = data.health;
}
}
[Serializable]
class PlayerData{
public float health;
}