- Home /
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();
}
}
Answer by Hellium · Aug 03, 2019 at 03:15 PM
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();
}
}
}
However after testing till finish. I've just realized that the winPopup.SetActive; function is broken. The log as per below:
ArgumentOutOfRangeException: Index was out of range. $$anonymous$$ust be non-negative and less than the size of the collection.
Too tired to continue now.. :-'( Thanks again for your help.
Give a try to the code in my answer I've fixed (PlayWorld function basically)
Answer by rodude123 · Aug 03, 2019 at 03:12 PM
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
The script is hooked up to an empty gameobject with a list of gameobjects with audiosource. A button is used to trigger the Playword() function.
Your answer