Search Unity

Null Exception Reference

Discussion in 'Getting Started' started by unity_YDXy-j36vRpfiQ, Nov 25, 2020.

  1. unity_YDXy-j36vRpfiQ

    unity_YDXy-j36vRpfiQ

    Joined:
    Nov 25, 2020
    Posts:
    3
    I have a NullExcep in this scrip in line 14:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class UI_Inventory : MonoBehaviour
    {
    private Inventory inventory;
    private Transform itemSlotContainer;
    private Transform itemSlotTemplate;

    private void Awake()
    {
    itemSlotContainer = transform.Find("itemSlotContainer");
    itemSlotTemplate = itemSlotTemplate.Find("itemSlotTemplate"); //Here is the problem!!!!
    }

    public void SetInventory(Inventory inventory){
    this.inventory = inventory;
    RefreshInventoryItems();
    }

    private void RefreshInventoryItems(){
    int x=0;
    int y=0;
    float itemSlotCellSize = 30f;
    foreach (Item item in inventory.GetItemList())
    {
    RectTransform itemSlotRectTranform = Instantiate (itemSlotTemplate, itemSlotContainer).GetComponent<RectTransform>();
    itemSlotRectTranform.gameObject.SetActive(true);
    itemSlotRectTranform.anchoredPosition = new Vector2(x * itemSlotCellSize,y * itemSlotCellSize);
    x++;
    if(x > 4){
    x=0;
    y++;
    }
    }
    }
    }
     
  2. bobbaluba

    bobbaluba

    Joined:
    Feb 27, 2013
    Posts:
    81
    Your problem is that itemSlotTemplate is null because you haven't assigned anything to it yet, but you are trying to call a method on it (Find), this is what causes the error.

    It's a bit hard to tell what the correct solution for you is, it depends on where the item you want to find is. If it's a prefab, you most likely want to make your itemSlotTemplate field public (or better, add [SerializeField] to it) and assign the property in the unity inspector.

    i.e.

    [SerializeField] private itemSlotTemplate;

    then select the game object with the script and drag-and-drop your template into the field "Item Slot Template" that should now be visible in the inspector.
     
    unity_YDXy-j36vRpfiQ likes this.
  3. unity_YDXy-j36vRpfiQ

    unity_YDXy-j36vRpfiQ

    Joined:
    Nov 25, 2020
    Posts:
    3
    Thanks, i solve that problem.