I'm trying to save and Load on my unity game on a file, I have no problem storing things like highScore, gold etc, but I can't store a list of a class called ObjectShop, I'm getting nullreference error.
I have a code where I can buyItems, they are objects with class ObjectShop, there I have all the information I need.
So when the buton is pressed I'm trying to add to the list the updated object for later store it in to my saveSystem, but getting an error on this line:
SystemDataController.systemDataController.powers.Add(itemListed);
Here is full script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BuyButton : MonoBehaviour
{
public int itemId;
public void BuyItem()
{
foreach (var itemListed in ArmorShop.armorShop.items)
{
//Can buy the item
if (itemListed.id == itemId && !itemListed.bought && GameControllerShop.gameControllerShop.RequestGold() >= itemListed.price)
{
//Set it to bought
itemListed.bought = true;
//Quit the money
GameControllerShop.gameControllerShop.RemoveGold(itemListed.price);
//Here I have the error: NullReferenceException: Object reference not set to an instance of an object
SystemDataController.systemDataController.powers.Add(itemListed);
SystemDataController.systemDataController.SaveData();
}
}
ArmorShop.armorShop.UpdateItem(itemId);
}
}
and that's what I have so far:
GameData.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class GameData
{
public float gold;
public float highScore;
public List<ObjectShop> powers = new List<ObjectShop>();
public GameData(SystemDataController game)
{
highScore = game.highScore;
gold = game.gold;
powers = game.powers;
}
}
SystemDataController.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SystemDataController : MonoBehaviour
{
public static SystemDataController systemDataController;
public float gold;
public float highScore;
public List<ObjectShop> powers = new List<ObjectShop>();
private void Awake()
{
systemDataController = this;
LoadData();
}
public void SaveData()
{
SaveSystem.SaveData(this);
}
public void LoadData()
{
GameData data = SaveSystem.LoadGame();
if (data != null)
{
gold = data.gold;
highScore = data.highScore;
powers = data.powers;
}
}
}
EDIT: I have read the link provided from here What is a NullReferenceException, and how do I fix it? and it doesn't talk about my problem, mine its about saving a custom class list on a file and also adding items to a possible null list?
EDIT2: Added object shop:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class ObjectShop
{
public int id;
public float price;
public string name;
public Sprite itemSprite;
public bool bought;
public string description;
public bool equipped;
}