Hello fellow programmers all around the world. I have been trying to create an inventory system for a while now and I think I've almost managed it but I get a wee bit of an error(I know that makes no sence in english!). Its a nullreference. here is the code:
using System.Collections;
using System.Collections.Generic; using UnityEngine;
public class Inventory : MonoBehaviour {
private RectTransform inventoryRect;
private float inventoryWidth;
private float inventoryHeight;
public int slots;
public int rows;
public float slotPaddingLeft;
public float slotPaddingTop;
public float slotSize;
public GameObject slotPrefab;
private List<GameObject> allSlots;
private int emptySlot;
// Use this for initialization
void Start () {
createLayout ();
}
// Update is called once per frame
void Update () {
}
private void createLayout(){
allSlots = new List<GameObject> ();
emptySlot = slots;
inventoryWidth = (slots / rows) * (slotSize + slotPaddingLeft) + slotPaddingLeft;
inventoryHeight = rows * (slotSize + slotPaddingTop) + slotPaddingTop;
inventoryRect = GetComponent<RectTransform> ();
inventoryRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, inventoryWidth);
inventoryRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, inventoryHeight);
int colums = slots / rows;
for (int y = 0; y < rows; y++) {
for (int x = 0; x < colums; x++) {
GameObject newSlot = (GameObject)Instantiate (slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform> ();
newSlot.name = "Slot";
newSlot.transform.SetParent (this.transform.parent);
slotRect.localPosition = inventoryRect.localPosition + new Vector3 (slotPaddingLeft * (x + 1) + (slotSize * x), -slotPaddingTop * (y + 1) - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, slotSize);
slotRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, slotSize);
allSlots.Add (newSlot);
}
}
}
public bool AddItem(Item item){
if (item.maxSize == 1) {
PlaceEmpty (item);
return true;
}
return false;
}
private bool PlaceEmpty(Item item){
if (emptySlot > 0) {
foreach (GameObject slot in allSlots) {
Slot temporary = slot.GetComponent<Slot> ();
if (temporary.isEmpty) {
temporary.AddItem (item);
emptySlot--;
return true;
}
}
}
return false;
}
}
The error is temporary but it looks fine to me and referenced(obviously not), so any help?