- Home /
what is good way to refer array in inspector.
I have 3 sound clips in inspector to change bgm while playing
so I defined below
public AudioClip[] bgmClip;
I assigned length '3' on Inspector and 3 clips also
then I need to get clip's length to check when clip's end
Awake()
{
if (bgmClip[0] != null)
{
audioCheck = bgmClip[0].length;
nextBgm = 1;
}
}
Update()
{
audioCheck -= Time.deltaTime;
if (audioCheck < 0)
{
audio.clip = bgmClip[nextBgm];
audio.Play ();
audioCheck = bgmClip[nextBgm].length;
if (nextBgm < bgmClip.Length-1)
{
nextBgm += 1;
}
else
{
nextBgm = 0;
}
}
}
It looks work well. but I am getting this error in console..
IndexOutOfRangeException: Array index is out of range.
GameController.Awake () (at Assets/Scripts/GameController.cs:163)
what is wrong? and Anyone know better way to keep play audio clips to cycle?
Answer by Scribe · Jan 11, 2015 at 06:38 PM
So I think the reason you are getting an error is because Awake is called during the initialization of variables and so bgmClip[0] does not yet exist, and hence even though you are trying to check if it is null to see if it exists, it won't be able to find any reference to it at all and won't be able to work out if it therefore does or does not return null as it doesn't exist!
Moving your awake stuff into Start should work, and possibly wrapping it in an if(bgmClip != null){ would help.
Just for variety here's an example of how you might do it with a coroutine!
public AudioClip[] audioClips;
void Start(){
StartCoroutine(LoopPlay(audioClips, 0));
}
IEnumerator LoopPlay(AudioClip[] aClips, int startIndex){
int index = startIndex;
while(true){
if(aClips == null){
yield return null;
continue;
}
if(aClips.Length < 1){
yield return null;
continue;
}
if(audio.isPlaying){
yield return null;
continue;
}
audio.clip = aClips[index];
audio.Play();
index = (index+1)%aClips.Length;
yield return null;
}
}
Hope that helps,
Scribe
Your answer
![](https://koobas.hobune.stream/wayback/20220613180125im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do you initialize a List or Array? 2 Answers
how to initialize multidimensional jagged array 1 Answer
Initializing an array of Vector3 in c sharp # 3 Answers
Why does my program crash when allocate and try to store variable in Vector3 array? 1 Answer
Parsing XML - appropriate array size 3 Answers