Play random audio clip

Hello,

I’m trying to attach a script to my character that plays a random audio clips every 10 seconds. It’s for a fighting game and the purpose is for characters to randomly say catch phrases during the fight. In the script below I keep getting an error saying no audio source.

using UnityEngine;
using System.Collections;

public class RandomSoundsScript : MonoBehaviour {

public AudioSource randomSound;

public AudioClip[ ] audioSources;

// Use this for initialization
void Start () {

CallAudio ();
}

void CallAudio()
{
Invoke (“RandomSoundness”, 10);
}

void RandomSoundness()
{
randomSound.clip = audioSources[Random.Range(0, audioSources.Length)];
randomSound.Play ();
CallAudio ();
}
}

Is everything connected properly?

Also note, Unity offers invokerepeating Unity - Scripting API: MonoBehaviour.InvokeRepeating
So you don’t have to recall your CallAudio method…

What do you mean by connected properly? Do you mean my speakers, yes. Other sounds work so thats not an issue. I’ve also dragged the clips I want to use into the script. I’m not sure what’s missing. I dragged the camera to the audio source and that didn’t work either.

Here is the error:

UnassignedReferenceException: The variable randomSound of Bytes has not been assigned.
You probably need to assign the randomSound variable of the Bytes script in the inspector.
Bytes.RandomSoundness () (at Assets/6 Scripts/Bytes.cs:24)

Well, that’s what I meant by connected…did you connect something to the randomSound variable?

I dragged the camera to it which contains the audio listener but I get the same error. Am I supposed to drag something else to it? I’m confused about what goes here.

You need an audiosource, not an audiolistener. Are you showing the same script because your error points to Bytes.cs and the code you posted shows RandomSoundsScript.

Your variable type is AudioSource. for randomSound which you set the audioClip on and then try to play.

It’s the same script I just changed the name to Bytes.

I added audio source to my character then attached the bytes script to the character and dragged some clips to it. It still doesn’t work and the audio source in the script is still blank but I attached it on my character already. What do I need to do, drag the character to the script to whom the script is already attached to?

Yes…The bytes script has the variable randomSound which in the inspector has no value. You need to drag an audiosource to it. If your character has an audiosource either you need to drag the character to it or assign the audiosource to the variable in awake/start using

randomSound = GetComponent();

This will work since you have both the audiosource and the script on the same object in the scene (your character in this case)
Otherwise, there is nothing assigned to the variable, so it doesn’t know what audiosource to use.

2 Likes

Awesome! Thanks for the help!