Foreach loop iterating only once? (Should be 3)

Literally that:

foreach(AudioClip newAudioClip in levelSoundFiles.pipeRifleShots)
{
	   Debug.Log(levelSoundFiles.pipeRifleShots.Count); //This Returns "3", but only Logs it once
	   GameObject audioObject=Instantiate(audioPrefab,audioParent);
	   AudioSource newAudioSource=audioObject.GetComponent<AudioSource>();
	   newAudioSource.clip=newAudioClip;
	   levelSounds.pipeRifleShots.Add(newAudioSource);
}

I, for the life of me cannot figure out why this happens. Excuses for the absolute horrifying code snippet.
(Also I should have 3 AudioObjects under the parent, but there is only one). Thanks in advance!

First make sure you’re not throwing errors.

Make sure your log console selector buttons are enabled. See this graphic:

Second make sure you don’t have COLLAPSE checked in the Console window.

If it still doesn’t work, rip ALL the code out except the Debug.Log() calls

Yeah, I am certain it does it only once, since both Collapse and the number on the right-hand-side of the log (ellipse with a number) would show multiple iterations.

Yes, removing all the code does make it work three times.

But I don’t see the issue with the current code.
All it does is adding the audioSource of a freshly added prefab to a list?

Well, I found the solution!
Apparantly, I needed to make the class of the variable levelSounds [System.Serializable]

I don’t know why. It works. I am not touching it.

Thanks for the reply as always!

FYI: I removed the 2D tag as this isn’t related to 2D features and added the Audio tag.

Adding a [System.Serializable] affects OTHER systems that might touch/change it, such as Unity or other serialization systems.

Here’s more reading.

Serialized / public fields in Unity are initialized as a cascade of possible values, each subsequent value (if present) overwriting the previous value:

  • what the class constructor makes (either default(T) or else field initializers, eg “what’s in your code”)

  • what may be saved with the prefab

  • what may be saved with the prefab override(s)/variant(s)

  • what may be saved in the scene and not applied to the prefab

  • what may be changed in the scene and not yet saved to disk

  • what may be changed in OnEnable(), Awake(), Start(), or even later

Make sure you only initialize things at ONE of the above levels, or if necessary, at levels that you specifically understand in your use case. Otherwise errors will seem very mysterious.

Here’s the official discussion: Serialization in Unity

If you must initialize fields, then do so in the void Reset() method, which ONLY runs in the UnityEditor.

Here’s more nitty-gritty on serialization:

Field initializers versus using Reset() function and Unity serialization:

To avoid complexity in your prefabs / scenes, I recommend NEVER using the FormerlySerializedAsAttribute