Argument out of range on a List?

Hi! I’m getting an error that I don’t understand. Here’s the code…

private List<GameObject> _activeNotifsList;

...

void Start () {
		_activeNotifsList = new List<GameObject>();
}

...

public void LerpNotifButtons(){
	//If an active notif exists in slot 0 and it is not yet at its target position, lerp it.
	if(_activeNotifsList[0] != null)
	{
           //Do something
       }
}

Where the if statement is returning the out of range error. Is it because the list doesn’t actually contain any elements yet?

This means that you have no elements in your list. You’re making a simple mistake in your reasoning. The list isn’t created infinite in length with all the entries set to null - there are no entries. There is a fundamental difference here. The word null has a very specific meaning, namely that an object has space reserved for it in the heap, but has nothing assigned to it yet. However, the list objects have no memory reserved for them at all. This is fundamentally different. You can refer to an object that exists, and a null check just tests if it has been initialised, but you cannot refer to something that doesn’t exist at all.

However, this list has no elements assigned. When you write _activeNotifsList[0], what are you asking it to look up? There is nothing reserved in memory - this object literally does not exist. You can’t compare it to anything because there’s nothing to compare. I hope you understand this.

So, what can you do instead? Well, you want to check if the list has any elements, so why not just use List.Count to count the number of elements in the list, and check if it is 0 or not? That is the most effective way to do what you seem to want to.

Where the if statement is returning the out of range error. Is it because the list doesn’t actually contain any elements yet?

Yes.

do

if(_activeNotifsList.Count > 0)
{
    //do something
}

instead.