Play a list of non-repetitive randomized audio with replay function.

The problem with this code is I’m unable to replay the current audio using the ReplayWord() function. It will however play the very next audio in list. Debug shows the same index number. Please help!


public class ShuffleAudioCircle : MonoBehaviour
{
  public GameObject winPopup;
  List<GameObject> audioList = new List<GameObject>();
  int randomIndex;
  void Start()
  {
    winPopup.SetActive(false);
    foreach (Transform t in transform)
    {
      audioList.Add(t.gameObject);
      t.gameObject.GetComponent<CircleCollider2D>().enabled = false;
    }
  }
  void PlayWord()
  {
    randomIndex = Random.Range(0, audioList.Count);
    Debug.Log(randomIndex);
    if (audioList.Count > 0)
    {
      audioList[randomIndex].GetComponent<AudioSource>().Play();
      audioList[randomIndex].GetComponent<CircleCollider2D>().enabled = true;
    }
    else
    {
      winPopup.SetActive(true);
    }
    audioList.RemoveAt(randomIndex);
  }
  public void ReplayWord()
  {
    Debug.Log(randomIndex);
    audioList[randomIndex].GetComponent<AudioSource>().Play();
  }
}

You are removing the gameObject after playing the song, so you can’t retrieve it afterwards.

 public class ShuffleAudioCircle : MonoBehaviour
 {
   public GameObject winPopup;
   List<GameObject> audioList = new List<GameObject>();
   int randomIndex = -1;
   void Start()
   {
     winPopup.SetActive(false);
     foreach (Transform t in transform)
     {
       audioList.Add(t.gameObject);
       t.gameObject.GetComponent<CircleCollider2D>().enabled = false;
     }
   }
   void PlayWord()
   {
     if (audioList.Count > 0 && randomIndex >= 0 )
           audioList.RemoveAt(randomIndex);

     if (audioList.Count > 0)
     {
       randomIndex = Random.Range(0, audioList.Count);
       Debug.Log(randomIndex);
       audioList[randomIndex].GetComponent<AudioSource>().Play();
       audioList[randomIndex].GetComponent<CircleCollider2D>().enabled = true;
     }
     else
     {
       winPopup.SetActive(true);
     }
   }
   public void ReplayWord()
   {
      if( audioList.Count > 0 && randomIndex >= 0 )
      {
         Debug.Log(randomIndex);
         audioList[randomIndex].GetComponent<AudioSource>().Play();
      }
   }
 }

Your PlayWord method is not being used anywhere try and use it in the update or fixedUpdate method. Lastly your for each loop

foreach (Transform t in transform)
{
    audioList.Add(t.gameObject);
    t.gameObject.GetComponent<CircleCollider2D>().enabled = false;
}

doesn’t make any sense, what is transform