- Home /
Question by
kweierer · May 31 at 02:28 PM ·
loadsave datainventory system
Saving a class List from another script
So i want to make an inventory Save and Load System, each item gets stored in a List of type Item. But when i try to acces that List i get an Nullrefernce Exception Error.
PlayerData Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PlayerData
{
public int money;
public List<Item> itemList;
public PlayerData(PlayerManager manager)
{
itemList = manager.inventory.itemList;
money = manager.money;
}
}
PlayerManager where the data gets Loaded:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerManager : MonoBehaviour
{
[SerializeField] public UI_Inventory uiInventory;
public Inventory inventory;
[Header("PlayerRelatedData")]
public int money;
private void Awake()
{
inventory = new Inventory();
uiInventory.SetPlayer(this);
uiInventory.SetInventory(inventory);
}
private void OnTriggerEnter2D(Collider2D collision)
{
ItemWorld itemWorld = collision.GetComponent<ItemWorld>();
if(itemWorld != null)
{
inventory.AddItem(itemWorld.GetItem());
itemWorld.DestroySelf();
}
}
public Vector3 GetPosition()
{
return gameObject.transform.position;
}
public void SavePlayer()
{
SaveSystem.SavePlayer(this);
}
public void LoadPlayer()
{
PlayerData data = SaveSystem.LoadPlayerData();
inventory.itemList = data.itemList;
money = data.money;
}
}
SaveSystem itself:
using System.IO;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveSystem
{
public static void SavePlayer(PlayerManager manager)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/player.savedData";
FileStream stream = new FileStream(path, FileMode.Create);
PlayerData data = new PlayerData(manager);
formatter.Serialize(stream, data);
stream.Close();
}
public static PlayerData LoadPlayerData()
{
string path = Application.persistentDataPath + "/player.savedData";
if (File.Exists(path))
{
BinaryFormatter formater = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
PlayerData data = formater.Deserialize(stream) as PlayerData;
stream.Close();
return data;
}
else
{
Debug.LogError("Save File not found in" + path);
return null;
}
}
}
Would be really thankful if anybody could help me here.
Comment
Your answer
Follow this Question
Related Questions
Save and load an inventory 0 Answers
Fail to load data from json to list of list. 1 Answer
How do I find a Prefab after I Replaced said Prefab? 1 Answer
Save and load data via Facebook SDK 0 Answers