Search code examples
classunity-game-engineinventory

Unity - "New" custom class instance isn't separated from other instance


Solved myself, I'm silly

Solved myself, I'm silly

Solved myself, I'm silly

See my answer below.

Having an issue with classes here, not sure of the cause.

In my scene I have 2 GameObjects being instantiated from the same prefab. Each has an InventoryManager script attached, and in this script I'm creating a new instance of a class called Inventory using inside InventoryManager:

using UnityEngine;
using System.Collections;

public class InventoryManager : MonoBehaviour {

    public Inventory inventory;
    private ItemDatabase itemDatabase;

    void Start () 
    {
        inventory = new Inventory (9);
    }
}

But for whatever reason, any of the List's values in my Inventory class is being shared between both of the instantiated GameObjects.

Here's a peak of the inventory class:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[System.Serializable]
public class Inventory
{
    public int ID;
    public List<Item> items = new List<Item>();
    public int maxSize;

    public static int inventoryCount;

    public Inventory(int size)
    {
        ID = inventoryCount;
        inventoryCount++;
        maxSize = size;
    }
}

Basically, when I add a new thing into

gameobject1.GetComponent<InventoryManager>().inventory.Add(item1);

(The add method does exist, it's a bit long so i'll only post it if requested)

It will also show up in gameobject2's inventory.


Solution

  • Alright so I feel like a total goof, and of course I would solve the issue after posting it.

    Basically, I made the very, very silly mistake of taking what my UI was displaying at face value, instead of using the inspector to see what was ACTUALLY in the inventory.

    The issue was with my UI showing the wrong stuff.