- Home /
Assign clip to audio source
Hello,
I have a prefab with an audiosource attached. The AudioClip variable box is empty, I want to assign it using a script.
Here's what I'm using to do that:
var clips : AudioClip[]; var rand = false;
function Start() { audio.clip = clips[Random.Range(0,clips.Length)]; RandSong(); } function Update() { if(rand) { RandSong(); rand = false; } } function RandSong() { audio.Play(); yield WaitForSeconds (audio.clip.length); audio.clip = clips[Random.Range(0,clips.Length)]; rand = true; }
Then, on the same prefab, I fill in a few slots of the clips[] array with music. However, nothing plays when I run my game.
Can anyone help me out?
It's not immediately clear to me based on what you posted why you're not hearing anything. $$anonymous$$aybe someone else will spot the problem, but in the meantime, I'd recommend doing some debugging. Do the tracks play correctly if you just attach them to an audio source component with 'play on awake' checked? Were the clips imported with '3D Sound' set to 'on'? Are they playing, but are just too far away from the listener to be audible? And so on.
Like Jesse asked; Did you attach the clip to the same part of the prefab where the script that calls to it is attached? Sounds like you did assign them in the Inspector window (need to do that as well). Also, if your camera isn't near the actual location of the clip (inherited transform of the objects within the parent obj), you won't hear it.
Answer by TiagoSerra · Oct 13, 2017 at 02:41 PM
Here Mate
Instructions: 1 - attach this to any gameobject 2 - place the gameobject with the AudioSource component to mySource 3 - Lets say you have 3 audio clips you want to use, set both Range Scan and My Audio Elements to 3 4 - add your 3 clips as elements 5 - Enable Debug to get a list of the clips on the console but they also show on the editor as you play the game
Tips: this is on enable, so everytime this object is enable its gonna run a new range and assign the clip, Hope it helps took me about 5 minutes, if this helps you please consider following my facebook dev group HERE
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class randomSound : MonoBehaviour {
public AudioSource mySource;
public int rangeScan;
public AudioClip[] myAudio;
public int toPlay;
public bool debugging;
void OnEnable () {
toPlay = Random.Range(0,rangeScan);
if (debugging) {
foreach (AudioClip value in myAudio) {
print (value);
}
}
mySource.PlayOneShot(myAudio[toPlay], 0.9F);
mySource.Play ();
}
}
Your answer
Follow this Question
Related Questions
Need help to play a random explosion sound from an array. 1 Answer
Stop audio from looping and play at lower volume 1 Answer
Playing audio from a GUI only app 0 Answers
Receiving float[][] instead of float[] for AudioClip.PCMReaderCallback 1 Answer
Loading MP3's into an Audio Array and assigning them to members of a GameObject Array 1 Answer