- Home /
Sounds when mouse is over
I want an object to play a sound when the mouse is over it I tried this
var soundP : AudioClip;
function OnMouseOver ()
{
if(AudioSource.clip != soundP)
{
AudioSource.clip = soundP;
}
if(!audio.isPlaying)
{
AudioSource.Play();
}
}
But I get this error : An instance of type 'UnityEngine.AudioSource' is required to access non static member 'clip'.
Help pls
Answer by Ashkan_gc · Jun 25, 2011 at 11:31 AM
you can access AudioSource component of your gameObject using audio property. attach an audioSource to your gameObject and even add a @RequireComponent tag to your script because any object that wants to play sounds should have an audio source attached.
var soundP : AudioClip;
function OnMouseOver()
{
if(audio.clip != soundp) audio.clip = soundP;
if (!audio.isPlaying)
{
audio.Play();
}
}
there is a play function that takes the audio clip to play as an argument, in that way you don't need to set the clip as the clip of the audio source. i think it was PlayOneShot. when you type AudioSource you are writing the name of the class which only allows you to access static variables/functions. you need the reference to the audio source component that you can get by using audio property.
to tell the script to attach an audio source automatically to your gameObject if it don't have any write this attribute in your script.
@RequireComponent(AudioSource)
in this way when you add this component an audiosource will be added autoamtically if needed.
It works if I put manually the AudioSource, but the @RequiereComponent(AudioSource) doenst work. I got this error: There is no 'AudioSource' attached to the "Cube1" game object, but a script is trying to access it. You probably need to add a AudioSource to the game object "Cube1". Or your script needs to check if the component is attached before using it.
Thnx
Your answer
![](https://koobas.hobune.stream/wayback/20220612121452im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Audio Repeating. 1 Answer
How to plan a game for unity? 2 Answers
Setting Scroll View Width GUILayout 1 Answer
Progresive sound ? 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers