Destroy method makes the code unable to assign GameObject variable

42 Views Asked by At
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class inventorySystem : MonoBehaviour
{
    public List<itemInstance> inventory = new();
    public inventorySlot[]  slots;
    public GameObject inventory_panel;
    public GameObject player;

    public void AddItem( item _item )
    {
      itemInstance new_item = new itemInstance();

      new_item.source_prefab = _item.source_prefab;
      new_item.quantity = _item.quantity;
      new_item.item_name = _item.item_name;
      new_item.item_description = _item.item_description;
      new_item.stackable = _item.stackable;
      new_item.item_icon = _item.item_icon;

      
      inventory.Add(new_item);
      UpdateInventory();

      Destroy(_item.gameObject);
    }

    public void RemoveItem(itemInstance itemToRemove)
    {
      inventory.Remove(itemToRemove);
    }

    private void Start() {
        
      slots = inventory_panel.GetComponentsInChildren<inventorySlot>();
    }
    
    public void UpdateInventory() {

      for (int i = 0; i < inventory.Count; i++)
      {
        slots[i].AssignImage(inventory[i]);
      }

    }

}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// itemInstance is the same just no inheritance

public class item : MonoBehaviour
{
    public int quantity;
    public bool stackable;
    public string item_name;
    [TextArea] public string item_description;
    public Sprite item_icon;
    public GameObject source_prefab;
}

sourceprefab exist in both script as a variable. I have no access issues, no nullreferenceexpections, it just doesnt work. other variables such as itemname or itemdescription get the values as intented. the only variable that stays null is the sourceprefab. but if I dont call the Destroy method or delay it, it works. but I dont want to delay it because you know, it can cause performance issues or unpredictable behaviours

0

There are 0 best solutions below