CodeBlanks Logo Icon CodeBlanks

Inventory list

Learn to hold inventory with List<Item>.

Storing Inventory with List<Item>

The C# List collection dynamically stores multiple objects of the same type. The List<Item> declaration creates a list that holds only objects of type Item. You can add new items as needed and access existing elements.

List<Item> items = new List<Item>();

Generic Collection Concept

List<T> is a generic collection type. The T inside angle brackets specifies which type of elements the list stores. When List<Item> is used, the list elements are Item objects. The System.Collections.Generic namespace must be included at the top of the file.

using System.Collections.Generic;
List<Item> items = new List<Item>();

Practice Create an Item List

Create a class named InventoryCollection. Include the System.Collections.Generic namespace and define an empty List<Item> field inside the class.

Starter code

Player.cs
using UnityEngine;

Sample solution

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

public class InventoryCollection
{
    public List<Item> items = new List<Item>();
}

Expected output

Envanter listesi oluşturuldu

Questions and answers

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

1 What is the main property of a List<Item> declaration?

  • Changing the number of lights in the scene
  • Starting an animation transition
  • Storing Item objects in a dynamic collection Correct answer
  • Storing only a single text value

Explanation: List<Item> is a dynamic collection of Item objects.

2 Generic List Type

Question
Yalnızca Item nesnelerini saklayan bir liste tanımlamak için ____ türü kullanılır.
Answer
Yalnızca Item nesnelerini saklayan bir liste tanımlamak için List<Item> türü kullanılır.

Explanation: List<Item> stores Item objects in an ordered collection.

3 Match List Components

Term Meaning
List Dynamic collection class
Item Object type stored in list
Count Number of list elements
System.Collections.Generic Namespace for generic collections

All lessons in Intermediate