CodeBlanks Logo Icon CodeBlanks

Inventory UI

Learn to build the inventory UI with prefabs.

Interface with prefabs

The inventory interface is made of a panel where the slots are lined up. The look of each slot is prepared as a prefab; this way the same look is used again and again. A prefab is a ready object template that can be added to the scene.

GameObject slotWidget;
// ...the same slot is used again and again

Thanks to prefabs the interface is duplicated quickly.

The slot widget

A slot widget is the interface part that shows one slot on the screen. It contains texts that show the item name and count. The inventory panel creates one widget copy for each slot.

[SerializeField] private GameObject slotWidget;

Widgets are produced from the prefab and added to the panel.

Practice Prepare the slot widget

In a class named SlotHazirlik, define a string widgetAdi field with the value "SlotWidget" and an int gorunenSlot field with the value 4. In the Start method, print the pieces "Widget: ", widgetAdi, " Gorunen: " and gorunenSlot joined together with Debug.Log.

Starter code

Player.cs
using UnityEngine;

public class SlotHazirlik : MonoBehaviour
{
    // string widgetAdi alanini "SlotWidget", int gorunenSlot alanini 4 degeriyle tanimla

    void Start()
    {
        // "Widget: " + widgetAdi + " Gorunen: " + gorunenSlot biciminde yazdir
    }
}

Sample solution

Player.cs
using UnityEngine;

public class SlotHazirlik : MonoBehaviour
{
    string widgetAdi = "SlotWidget";
    int gorunenSlot = 4;

    void Start()
    {
        Debug.Log("Widget: " + widgetAdi + " Gorunen: " + gorunenSlot);
    }
}

Expected output

Widget: SlotWidget Gorunen: 4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is the look of each slot created in the inventory interface?

  • They are shown with light effects
  • Separate code is written for each slot
  • A prefab is prepared and used again and again Correct answer
  • The slots are colored automatically

Explanation: A prefab reproduces the same look, so code does not have to be written again for every slot.

2 Write the type of the widget object

Question
    [SerializeField] private ____ slotWidget;
Answer
    [SerializeField] private GameObject slotWidget;

Explanation: Because the slot widget is an object that can be added to the scene, it is held as a GameObject type.

3 Interface terms

Term Meaning
Prefab A reusable object template
Slot widget The interface part that shows one slot
Panel The area where the slots are gathered
Metin alanı Part showing item name and count

All lessons in Advanced