JThistle
JThistle

Reputation: 128

A list initialised in C# has elements in it already

In Unity, whilst using C#, I initialised a list:

public List<int> sequence = new List<int>();

However, I noticed that when using the list later, it had more elements than I expected. I ran this code to debug it:

void Start () {
        Debug.Log(sequence.Count);
        sequence.Clear ();
        Debug.Log(sequence.Count);
        sequence.Add (0);
        sequence.Add (1);
        sequence.Add (2);
        sequence.Add (3);
        Debug.Log(sequence.Count);
}

This gave the output of:

4
0
4

I would have expected the output to be 0 0 4, since the list should be created with 0 elements in it.

For some reason that I haven't been able to work out, the list is being created with 4 elements in it.

Firstly, can anyone reproduce this at all? And secondly, can anyone work out why this is happening (it's easily fixable enough with sequence.Clear())?

Thanks in advance!

Upvotes: 0

Views: 81

Answers (2)

JThistle
JThistle

Reputation: 128

Turns out that for whatever reason, the list had the number of elements set to 4 in the inspector. Thanks everyone for the help.

Upvotes: 0

piojo
piojo

Reputation: 6723

In Unity3D, a public field which is serializable is the same as putting the [SerializeField] attribute before the field's declaration. If this field is part of another serializable class (usually a MonoBehaviour), Unity will store the values in the object. The values are saved by the editor (when the game isn't running), stored on disk, and loaded again whenever you open the project. When you instantiate your object in the scene, that object will also have a copy of the public/serialized variable.

So to check if you've specified values for this object, find the MonoBehaviour it belongs to in the editor. Don't look for the script. Look for the GameObject. Scroll down to where sequence is shown in the inspector. Are there values specified? If so, those values will always be present after the object containing the script (the component) is instantiated.

Upvotes: 1

Related Questions