Why does waveWayPoint need to be set to a new list?

In the video, we create a variable inside of a method:

var waveWaypoints = new List< Transform >();

I know we’ve done something similar with Vector2, but I’ve never really understand why we need to use “new”. Could someone explain what is going on here?

Why doesn’t “List< Transform > waveWaypoints” work instead?

Full method:

public List<Transform> GetWaypoints()
{
    var waveWaypoints = new List<Transform>();
    foreach (Transform child in pathPrefab.transform)
    {
        waveWaypoints.Add(child);
    }
    return waveWaypoints;
}

Thank you!

I found someone who explained it.

its the difference between saying you have a picture(reference) or your at the place, (instance) think of it this way. lets say that list wasnt a list, it was just an int.
i can say int i;
and i have a reference, but the reference is empty, i.e. it has no value.
but if i say int i = 0;
it now has value, without the zero i cant act on i because the computer dosnt know what do do with it…
so basicaly saying List list;
and not List list = new List()
means you have declared that variable, and allocated space in memory, but it dosnt mean anything, until you assign a value. hope this helps.
You cannot use uninitialized variables in C#. You can initialize a variable with the default value of its type. You also can use the default value of a type to specify the default value of a method’s optional argument. - Technivorous

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms