setting Values to gameObjects in an Array

Hi guys.
So my problem is, i want to set values to gameObject in an array.
These gameObjects share a script called playSongItemScript and within this script there is a public int called songIndex (which determines which song the gameObject plays when it collides with the player)…
But the problem is all gameObjects with this script are set to the same values although the values should change as is in my for-loop below.

  void setMusicTracks(){
      for(int z = 0; z < chosenMusicPool.Count; z++){
        //playSongItemScript songScript;
        GameObject musicInstance = chosenMusicPool[z];
        musicInstance.GetComponent<playSongItemScript>().songIndex = z;
        //songScript = musicInstance.GetComponent<playSongItemScript>();
       Debug.Log("z = "+z);
       
      // songScript.songIndex = z;

      }
    }

How can i fix it?
the value for song index is always the Count of my chosenMusicPool List.

1 Answer

1

You should make is a list of playSongItemScript, using GetComponent in a loop is slow. Also you are looping through and setting them all to the same value. EDIT: Actually not sure if you are setting them to the same, on further inspection seems fine… try more debug logs.

List chosenMusicPool;

for(int z = 0; z < chosenMusicPool.Count; z++)

{

chosenMusicPool[z].songIndex = z;

}