List<> strange behaviour
Hello there,
I've got a strange behaviour on a simple List where I want to add items. I have an InventoryController class and a WorldController class, the Items call the AddToPlayerInventory() method.
public class PlayerInventoryController : MonoBehaviour
{
private List<CollectibleWorldObject> inventoryItems = new List<CollectibleWorldObject>();
public CollectibleWorldObject activeItemObject;
private int activeItem = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("x"))
SwitchItems();
if (Input.GetKeyDown("c"))
{
foreach (var obj in inventoryItems)
{
print(obj.ItemType);
}
}
}
public void AddItem(CollectibleWorldObject item)
{
print("item added: " + item.ItemType);
this.inventoryItems.Add(item);
if(inventoryItems.Count == 1)
{
SwitchItems();
}
print(inventoryItems.Count);
}
}
public class WorldController : MonoBehaviour
{
private static List<BaseWorldObject> worldObjects = new List<BaseWorldObject>();
private PlayerInventoryController inventoryController;
// Start is called before the first frame update
void Start()
{
BaseWorldObject baseObj;
var currentScene = SceneManager.GetActiveScene();
inventoryController = GameObject.FindGameObjectWithTag("Player1").GetComponent<PlayerInventoryController>();
foreach (GameObject obj in currentScene.GetRootGameObjects())
{
if (obj.TryGetComponent<BaseWorldObject>(out baseObj))
{
baseObj.ItemName = obj.name;
worldObjects.Add(baseObj);
print(baseObj.ItemType);
}
}
}
public void AddToPlayerInventory(CollectibleWorldObject obj)
{
inventoryController.AddItem(obj);
worldObjects.Remove(obj);
}
}
Somehow, the inventoryItems List does not get updated (if I change it to static, it works!). The part "print(inventoryItems.Count);" prints more and more items but if I try to SwitchItems() (which works if static) the List seems to be empty, inventoryItems.Count is zero in the SwitchItems() method. The List in the WorldController should also be non static if possible, but it's the same strange behaviour... This is one of my first attempts to develop a game in Unity... so... what the hell is happening here? ^^
Thanks in advance!
Comment