Unity: Use Foreach with Debug.log to Debug a List

Introduction
You need to be capable of quickly debugging a list while developing your game. To do so, you will use a combination of the foreach statement and the Debug.Log method. This guide will teach you how.
What is a list in C#?
A list is a collection. A list represents a number of ordered values. A list allows the same value to occur more than once. Lists are one-dimensional.
There are many types of collections in C#. Here are some examples of other collections:
- Array
- Stack
- Queue
- Hashtable
- C# Dictionary
📄 Resources:
Foreach in C#
foreach is a statement that iterates over each element of a collection. The foreach statement consists of two parts: the statement and the body. The statement describes the set to iterate. The body describes what to execute for each item in the set.
In pseudocode:
foreach item in list do something
Foreach with Debug.Log
Basic foreach Example
The foreach loop is a fundamental construct for iterating over collections in C#. In the context of Unity, this loop makes it easy to traverse a set of elements contained in a list.
Logging the progression of the iteration provides real-time insights into the loop’s execution.
The basic example showcases its simplicity:
List<string> myList = new List<string>() {
"Alpha",
"Beta",
"Gamma"
};
foreach (string s in myList )
{
Debug.Log($"Processing: {s}");
}
Conditional Logging
You can use a conditional statement in the body of your foreach loop. Use a conditional to to selectively log information based on specific criteria. In this example, items starting with ‘A’ are singled out for logging:
List<string> myList = new List<string>() {
"Alpha",
"Beta",
"Gamma"
};
foreach (string s in myList )
{
if (s.StartsWith("""))
{
Debug.Log($"Found item starting with 'A': {s}");
}
}
Logging Index and Value
The foreach loop does not include the index to the body. But, you may need the index to confirm that the code is executing properly. To access the index, you have two options:
- Use a for loop.
- Initialize an integer outside of the foreach scope, then increment it each iteration.
Here’s how to use a for loop:
List<string> myList = new List<string>() {
"Alpha",
"Beta",
"Gamma"
};
for (int i = 0; i < myList.Count(); i++)
{
Debug.Log($"Index: {i}, Value: {myList[i]}");
}
📄 Resources:
Create a free account, or log in.
Gain access to free articles, game development tools, and game assets.