Can't add child Transforms to private List, but public List works fine

Hello!

So I’ve made a script that automatically adds child objects to a list on Start().

Here’s what I’m doing:

public List<Transform> WalkFrames;

void Start()
{
    foreach (Transform child in WalkFramesParent)
        {
            Debug.Log("Found child: " + child.name);
            WalkFrames.Add(child); //This is where the error is
            WalkFramesLength++;
        }
}

Now if I make the List public, it works great. However, if it’s private, I get this error (even though the Debug.Log fires once):
NullReferenceException: Object reference not set to an instance of an object
CharachterAnimator.Start () (at Assets/CharachterAnimator.cs:33)

Any idea as to why this happens? It really doesn’t inhibit me much, this question is just out of personal curiosity.

Thanks.

1 Like

serialized Lists and arrays are automatically initialized by the inspector if they weren’t in code.
fields that aren’t serialized are your responsibility to ensure are initialized.

be sure to initalize it with “new List<?>()” or “new ?[ ]”.

private List<Transform> WalkFrames = new List<Transform>();
3 Likes