Howdy all,
I use a C# List to store inventory items. This list is in a script that is preserved between scenes using DontDestroyOnLoad I call PRIMARY. All of the inventory management code works just fine when testing the scenes on their own, but when I add an item in one scene, and try to use the item in the next scene, the elements on the list return null. An item on the List that one scene ago returns a valid tostring, now returns null and breaks the scripts. I can see that there are items attached to the list in the inspector, oddly enough.
There’s probably a really obvious answer to this, but I can’t say I found it. If Lists straight up don’t work between scenes, that would be good to know too.
Relevant code portions:
PRIMARY (where the list is)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
public class PRIMARY : MonoBehaviour {
public static PRIMARY Instance;
public List<Item> Inventory = new List<Item>();
void Awake()
{
}
if (Instance == null)
{
DontDestroyOnLoad(gameObject);
Instance = this;
}
else if (Instance != this)
{
Destroy(gameObject);
}
}
}
Item Class for the objects in the list:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class Item : Component
{
public string itemname { get; set; }
public int count { get; set; }
public int itemid { get; set; }
public Item(string tx, int c, int id)
{
this.itemname = tx;
this.count = c;
this.itemid = id;
}
public Item()
{
this.itemname = "";
this.count = 0;
this.itemid = 0;
}
public override string ToString()
{
return "" + itemname + " X" + count;
}
}
Code where the items from the previous scene return null:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class Manufacturing : MonoBehaviour {
public GameObject scriptc;
public PRIMARY primaryscript;
void Start () {
StartCoroutine(attachinventory());
}
IEnumerator attachinventory()
{
yield return new WaitForSeconds(.31f);
scriptc = GameObject.Find("SCRIPTSC"); //(GameObject PRIMARY is attached to)
primaryscript = scriptc.GetComponent<PRIMARY>();
Debug.Log(primaryscript.Inventory[0]);
}
Any help is greatly appreciated, thank you for your time.