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!
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?
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.