- Home /
Playing sound on an Instantiated Prefab
Hello everyone. I'm fairly new to Unity but pretty advanced in other scripts such as JS and AS. So I have a prefab with this script attached:
#pragma strict
var prospectTime : int;
var prospectAudio : AudioClip;
private var time : float = 0.0f;
function OnMouseDown () {
if (Vector3.Distance(transform.position, GameObject.FindGameObjectWithTag("Player").transform.position) < 6)
time = 0.1f;
}
function Update () {
if (time > 0) {
time += 1 * Time.deltaTime;
}
if (time > prospectTime) {
activate();
}
}
function activate () {
var zone : Zone = transform.parent.transform.parent.transform.parent.GetComponent(Zone);
var a = transform.parent.transform.parent.name.Split(":"[0]);
if (zone.activateData(transform.parent.name, int.Parse(a[1]), int.Parse(a[2])) == true) {
AudioSource.PlayClipAtPoint (prospectAudio, transform.position);
transform.parent.active = false;
}
time = 0.0f;
}
function OnMouseUp () {
time = 0.0f;
}
This works, however if i try to play the sound with
audio.Play(prospectAudio);
it will throw an error:
BCE0023: No appropriate version of 'UnityEngine.AudioSource.Play' for the argument list '(UnityEngine.AudioClip)' was found.
audio.PlayOneShot(prospectAudio);
also throws an error:
MissingComponentException: There is no 'AudioSource' attached to the "Coal1" game object, but a script is trying to access it.
In inspector I did drag the audio on the script's prospectAudio variable.
What's wrong? I would like to use the audio.Play and audio.PlayOneShot but it seams I can't :)
Can someone explain please?
Answer by MicroEyes · Jul 12, 2013 at 07:09 AM
You'll have to attach AudioSource Component to 'Coal1' gameobject from Unity Menu Components->Audio->Audio Source. Thats why you are getting this Error:
MissingComponentException: There is no 'AudioSource' attached to the "Coal1" game object, but a script is trying to access it.
Answer by Vampiressae · Jul 12, 2013 at 07:53 AM
Thank you for your quick reply. I attached the audio component as you said (same audio as in the script's AudioClip), I don't get an error but I don't hear the sound either :( Mute, Bypass, Play on awake and Loop are unchecked and the distance is between 1 and 500.
Your answer
Follow this Question
Related Questions
video texture plays too fast when adding audio 2 Answers
Background Music 2 Answers
Play Oneshot Audio On Touch 0 Answers
Audio.Play() not showing up 1 Answer
How do I play audio source on Maximize on Play / Audio Source wont play on Maximize 0 Answers