Address
304 North Cardinal St.
Dorchester Center, MA 02124

Work Hours
Monday to Friday: 7AM - 7PM
Weekend: 10AM - 5PM

Unity list length

Unity List Length

On Unity, list length can be retrieved by code using a property.

Table of contents

Unity – Get list length?

To retrieve the length of a list in Unity, use the Count property: int length = myList.Count;

Here’s a concrete example:

var myList = new List<int>() { 5, 4, 3, 2, 1 };
int length = myList.Count;

In C# and Unity, the Length property is used for arrays, while for lists, the Count property should be used.

For further information on lists, please consult : Unity List Collection: A Comprehensive Guide

Using LINQ Method

It’s also possible to use LINQ to retrieve the length of a list by using the extension method Count.

However, it’s not recommended due to potential performance issues as it may resort to enumeration if the Count property is not available.

What to do with the length of a list?

The length of a list can be utilized for various purposes.

The most common use is to iterate through the elements of a list using a for loop.
For example:

var myList = new List<int>() { 5, 4, 3, 2, 1 };
for (int i = 0; i < myList.Count; i++)
{
    int number = myList[i];
}

Tips: Instantiate a list with known length

For better performance, when instantiating a list with a known length, it’s advisable to set the capacity explicitly.

This can be done by passing an integer to the list constructor, like this: var myList = new List<int>(50);

Indeed, when the list reaches its maximum capacity, it has to be resized to accommodate more elements, which may mean copying all existing elements to a new memory area.
This can be costly in terms of performance, especially if the list undergoes numerous add operations.

FAQ

How to check list length in Unity?

To retrieve the length of a list in Unity, use the property Count: int length = myList.Count;

What is the capacity of a list in Unity?

In Unity, the capacity of a list defines the number of elements that the list can have without requiring resizing.
Capacity can be set during list instantiation or accessed and modified using the Capacity property.

How do I limit a list in Unity?

The best solution is to use an array, as they have a fixed size defined during creation.
It’s also possible to create a custom list class based on the source code, where you would modify the “Add” method and the functioning of “Capacity.”
However, this approach can be complex.

Learn more

Leave a Reply

Your email address will not be published. Required fields are marked *