- Home /
Array of AudioClips not playing, please help
Hi all,
I have an array of 4 sounds added as an audioclip array:
public AudioClip[] sounds;
and I initialise it in Start() like so:
for (int i=0; i<4; i++)
{
sounds = new AudioClip[i];
}
Later on in my code I want to play a random sound from that bank. My object has an audiosource attached. The code I am using is:
audio.clip = sounds[Random.Range(0, sounds.Length)];
audio.Play();
The sounds are assigned in the inspector yet when my scene runs none of the sounds play.
What am I doing wrong?
Thanks in advance,
Martin
Yeah I removed the initialization and it worked first time. I was under the understanding that you had to initialize each array position before you could use it :D
FYI, this should have been a comment ins$$anonymous$$d of an answer.
In general you do have to initialize both the array as a whole and the individual elements. The way you went about the initialization it is wrong for general initialization. But you have a public variable and you set of the array size in the inspector and drag and drop items into the array into the inspector, Unity does this initialization for you.
Answer by robertbu · Feb 21, 2013 at 06:54 PM
Your problem is here:
for (int i=0; i<4; i++)
{
sounds = new AudioClip[i];
}
Just kill this initialization. This is recreating the array four times, each time a little longer, but in the process it blows away the original clips you assigned in the inspector.
Answer by wholebitmedia · Feb 21, 2013 at 07:19 PM
You might try a case statement for this idea. I remember having a lot of issues with audio when I was learning it. In any case, if you are using C# you might need to indicate the desired audio inside the parenthesis after your Play command.
audio.Play(walk); or audio.PlayOneShot(land);
anyone else feel free to "chime" it!?
Tha5 was just a little programming humor! :)
Answer by Unity-Devloper · Jun 17, 2020 at 06:27 AM
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/// <summary>
/// Class in charge to play sound in the game
/// </summary>
public class SoundManager : MonoBehaviour
{
public AudioSource GamePlaySound;
/// <summary>
/// Reference to the jump sound
/// </summary>
public AudioClip[] soundClips;
/// <summary>
/// Reference to the audiosource who will play the sounds
/// </summary>
AudioSource audioSource;
void Awake()
{
audioSource = GetComponent<AudioSource> ();
}
public void PlaySoundClip()
{
audioSource.PlayOneShot(soundClips[Random.Range(0,soundClips.Length)]);
;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613093128im_/https://answers.unity.com/themes/thub/images/avi.jpg)