I've been following this tutorial series: https://www.youtube.com/watch?v=LcizwQ7ogGA&list=PLJWSdH2kAe_Ij7d7ZFR2NIW8QCJE74CyT&index=3 I'm on part 3 of 10.
Good series so far, however I've hit a very major problem. When I go over to pick an item up, it recreates the item, indefinately causing the enitre game to lag very quickly, Figure 1. I'm not sure what else to do as anything I do doesn't fix it at all. Is there anything anytone can spot that is wrong or that is causing this? The only error I get is that Line 48's object reference is not set to an instance of an object, Figure 2. This might be because I have a new prefab in the Inspector, Figure 3.
Here is the code for Display Inventory:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DisplayInventory : MonoBehaviour
{
public GameObject inventoryPrefab;
public InventoryObject inventory;
public int xStart;
public int yStart;
public int xSpaceBetweenItem;
public int numberOfColumns;
public int ySpaceBetweenItem;
Dictionary<InventorySlot, GameObject> itemsDisplayed = new Dictionary<InventorySlot, GameObject>();
// Start is called before the first frame update
void Start()
{
CreateDisplay();
}
// Update is called once per frame
void Update()
{
UpdateDisplay();
}
public void UpdateDisplay()
{
for (int i = 0; i < inventory.Container.Items.Count; i++)
{
InventorySlot slot = inventory.Container.Items[i];
if (itemsDisplayed.ContainsKey(slot))
{
itemsDisplayed[slot].GetComponentInChildren<Text>().text = inventory.Container.Items[i].amount.ToString("n0");
}
else
{
var obj = Instantiate(inventoryPrefab, Vector3.zero, Quaternion.identity, transform);
obj.transform.GetChild(0).GetComponentInChildren<Image>().sprite = inventory.database.GetItem[slot.item.id].uiDisplay;
obj.GetComponent<RectTransform>().localPosition = GetPosition(i);
obj.GetComponentInChildren<Text>().text = slot.amount.ToString("n0");
itemsDisplayed.Add(inventory.Container.Items[i], obj);
}
}
}
public void CreateDisplay()
{
for (int i = 0; i < inventory.Container.Items.Count; i++)
{
InventorySlot slot = inventory.Container.Items[i];
var obj = Instantiate(inventoryPrefab, Vector3.zero, Quaternion.identity, transform);
obj.transform.GetChild(0).GetComponentInChildren<Image>().sprite = inventory.database.GetItem[slot.item.id].uiDisplay;
obj.GetComponent<RectTransform>().localPosition = GetPosition(i);
obj.GetComponentInChildren<Text>().text = slot.amount.ToString("n0");
itemsDisplayed.Add(slot, obj);
}
}
public Vector3 GetPosition(int i)
{
return new Vector3(xStart + (xSpaceBetweenItem * (i % numberOfColumns)), yStart + (-ySpaceBetweenItem * (i / numberOfColumns)), 0f);
}
}