- Home /
Why does sound attached to gameobject is not playing at desired time?
Hey! I am having an animator gameobject to which I have attached a sound source. I need the audio to be played when I click my gameobject. Here is my code.
public class destroy : MonoBehaviour {
private AudioSource source;
void Update () {
}
void OnMouseDown(){
source = GetComponent<AudioSource>();
source.Play ();
//source.PlayOneShot ((AudioClip)Resources.Load("BOING_"));
}
}
The sound is being played. But the problem is it is getting played well before I click them. To be more precise its being played when the game starts. Please help me in solving this. Thanks in advance!! :)
check the audio source object if the Play on awake box is ticked.
Oh. Thanks for pointing out that :) But still, the sound would not play when I am clicking down on the gameobject. How to solve that one.?
Place a Debug.Log("clicked") in your On$$anonymous$$ouseDown Function to see if it is even called.
Does your object have a collider? On$$anonymous$$ouseDown needs one if you are not doing a GUIElement interaction.
Yes it do have a collider. Btw. This code is attached to a prefab. This prefab is instantiated multiple times as gameobjects. Just in case this information would lead you to help me. :)
Answer by error031 · May 31, 2015 at 03:49 PM
Thats because OnMouseDown is called only when you are pressing mouse button. You should do something like this:
private AudioSource source;
void Update () {
}
void OnMouseDown(){
source = GetComponent<AudioSource>();
PlaySound();
}
void PlaySound(){
source.Play ();
}
Thanks for replying :) That is what I need. I just want the sound to be played when the mouse is clicked on the game object. That would make code a proper one right? Sorry. I might be wrong. Please guide me by explaining ur statement. :) Btw, even after trying your code it is not working.
That is the exact same code as the one in the question but the Source.Play() is in a function. If On$$anonymous$$ouseDown() is not called, then PlaySound() will not work either.
@abhishekabz004 , Try putting a Debug.Log into your On$$anonymous$$ouseDown() Function to see if it is called.
I have done that before. Its getting called. There is no problem in it. Even when I tried the PlaySound() method, it got called either. But still the sound is not playing.