Playing audioclip on mouseover?

var myClip : AudioClip ;

function OnMouseOver () {
		audio.PlayOneShot(myClip);
}

This works, but it plays the sound each millisecond, which is definitely not what I want. I tried to fix this by using booleans:

var myClip : AudioClip ;
var Over : boolean = false;

function Update () {
	if(Input.OnMouseOver(0)) {
		Over = true;
	}else{
		Over = false;	
}

function Update () {

	if ( Over = true ) {
		audio.PlayOneShot(myClip);
}

But now it’s whining about a bunch of syntax errors. All I want is to play a sound once when moving the cursor over an object, like a button. Please help.

Try below, I have also optimized the codes. If still got errors, please post out.

var myClip : AudioClip ;
var Over : boolean;

function OnMouseOver(){
        Over = true;
}
function OnMouseExit(){
        Over = false;
}

function Update () {
    if (Over)
       audio.PlayOneShot(myClip);
}

I believe your second version should work, however, you are missing a few brackets and you cannot have 2 function update calls. You need to combine everything you want in update in one call. The correct code is below:

var myClip : AudioClip ;
var Over : boolean = false;

function Update () {
if(Input.OnMouseOver(0) && Over == false) {
Over = true;
}
else if{nput.OnMouseOver(0) && Over == true){
Over = false;
}
if ( Over == true ) {
audio.PlayOneShot(myClip);
}
}

I believe this should work. If it doesn’t, I am sure somebody else will know what is wrong.

I’m not going to write any code, but do this:

  1. take your first version.
  2. add a variable like ‘IsOver’
  3. Set the variable to true on OnMouseOver
  4. Set the variable to false in OnMouseOff
  5. In OnMouseOver, before you set IsOver to true, if it is currently false, play the one shot.

The idea is that you want to play the sound the first time, and only the first time, OnMouseOver is called for the duration you’re over the object.

Here try this:

var myClip : AudioClip ;
var Over : boolean = false;

function Update (){
    if(Input.OnMouseOver(0)) {
        Over = true;
	}else{
		Over= false;
	}
}

function Update (){
    if ( Over == true ) {
		if (audio.isPlaying != true){
        audio.PlayOneShot(myClip);
		}
	}
}

Wrong event, pals! The correct one is OnMouseEnter, because OnMouseOver is called while the mouse is over the object:

var myClip : AudioClip ;

function OnMouseEnter() {
     
	audio.PlayOneShot(myClip);
}