- Home /
Question by
nekros974 · Jul 21, 2017 at 08:04 AM ·
c#coroutineaudiosource
Crash/Bug when I want to play a song while I walk
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundManager : MonoBehaviour {
public AudioClip[] g_fstep_walk = new AudioClip[6];
public AudioClip[] g_fstep_run = new AudioClip[8];
int minRandom;
int maxRandom;
int song;
IEnumerator coroutine;
public void PlaySong(int i, AudioSource p_song, bool w)
{
coroutine = test(i,p_song);
while(w){
StartCoroutine(coroutine);
}
}
IEnumerator test(int i, AudioSource test)
{
test.clip = g_fstep_walk[i];
test.PlayDelayed(1f);
test.Play();
yield return new WaitForSeconds(1f);
}
}
Comment
Answer by Garazbolg · Jul 21, 2017 at 08:57 AM
Ok so there are a few things wrong with your code, but mainly you have an infinite loop
IEnumerator coroutine;
public void PlaySong(int i, AudioSource p_song, bool w)
{
coroutine = test(i,p_song);
while(w){ // <= w is never set to false and this function isn't a coroutine so it won't stop looping and thus keep your thread eternaly
StartCoroutine(coroutine);
}
}
Also I'm not really sure you are Trying to achieve with this script.
Are you trying to do a manager to play a random sound for each step ?
But to fix you code without changing too much i'd go :
IEnumerator coroutine;
public bool w = false;
public void PlaySong(int i, AudioSource p_song)
{
w = true;
coroutine = StartCoroutine(test(i,p_song));
}
IEnumerator test(int i, AudioSource test)
{
while(w){
test.clip = g_fstep_walk[i];
test.PlayDelayed(1f);
test.Play();
yield return new WaitForSeconds(1f);
}
}
At least it shouldn't crash. Also I'd remove the new Audioclip[];
statements because you don't need those if you're setting the audioSources in the inspector.
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Fade, Then Stop all other audiosources attached to gameobject? 1 Answer
Change AudioSource output via Script 1 Answer
Audio Manager or not? Audio System 0 Answers