CodeBlanks Logo Icon CodeBlanks

Printing the inventory

Learn to print the inventory contents with Debug.Log.

Printing Inventory Contents

The Debug.Log method prints a message to the Unity Console window. To display inventory item information, you can iterate through each element and print the fields you need as text. This method makes it easier to inspect data during development.

Debug.Log(item.itemName);

Iterating Through a List with foreach

The foreach loop visits the elements in a collection one by one. The loop variable represents the current element in each iteration. When used with List<Item>, you can access one Item object during each iteration.

foreach (Item item in inventory)
{
    Debug.Log(item.itemName);
}

Practice Print Inventory Contents to the Console

Define a list of Item objects in the InventoryPrinter class. In the PrintItems method, use foreach to print the itemName field of every item in the list with Debug.Log.

Starter code

Player.cs
using UnityEngine;
using System.Collections.Generic;

public class InventoryPrinter : MonoBehaviour
{
    public List<Item> inventory = new List<Item>();

    
}

Sample solution

Player.cs
using UnityEngine;
using System.Collections.Generic;

public class InventoryPrinter : MonoBehaviour
{
    public List<Item> inventory = new List<Item>();

    public void PrintItems()
    {
        foreach (Item item in inventory)
        {
            Debug.Log(item.itemName);
        }
    }
}

Expected output

Potion
Key
Shield

Questions and answers

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

1 Which structure is suitable for printing the name of every inventory item to the Console window?

  • A foreach loop and Debug.Log Correct answer
  • Only the Transform component
  • Animator transition settings
  • Creating a folder in the Project window

Explanation: foreach iterates through each Item in the list while Debug.Log prints the information to the console.

2 Printing a Message to the Console

Question
Unity'de bir metin mesajını Console penceresine yazdırmak için ____ metodu çağrılır.
Answer
Unity'de bir metin mesajını Console penceresine yazdırmak için Debug.Log metodu çağrılır.

Explanation: Debug.Log prints text or variable values to the Unity Console window.

3 Match the Printing Process

Term Meaning
foreach Iterates through collection elements
item Current item object in the loop
itemName Field storing the item's name
Debug.Log Sends message to Unity Console

All lessons in Intermediate