Play sound only when button is pressed
I want to play sound only when button is pressed but i don't know how to do it.
Any ideas?
Button script that i'm using.
using UnityEngine;
using System.Collections;
public class ButtonSound : MonoBehaviour
{
bool isOn;
public Transform Button;
public AudioClip beep;
private AudioSource source;
void Start ()
{
source = GetComponent<AudioSource>();
}
public void OnMouseUp()
{
GetComponent<Renderer>().material.color = Color.gray;
Button.transform.localPosition = new Vector3(0, 0.2f, 0);
}
public void OnMouseDown()
{
GetComponent<Renderer>().material.color = Color.green;
Button.transform.localPosition = new Vector3(0, 0.2f, 0);
isOn = !isOn;
if (isOn)
{
//don't play sound???
}
else
{
//play sound???
}
}
}
Comment
Best Answer
Answer by Anonymou5 · Sep 30, 2016 at 01:13 PM
I know how to do it!
This script does work just like i wanted.
using UnityEngine;
using System.Collections;
public class ButtonSound : MonoBehaviour
{
public Transform Button;
public void OnMouseUp()
{
GetComponent<Renderer>().material.color = Color.gray;
Button.transform.localPosition = new Vector3(0, 0.2f, 0);
this.GetComponent<AudioSource>().Stop();
}
public void OnMouseDown()
{
GetComponent<Renderer>().material.color = Color.green;
Button.transform.localPosition = new Vector3(0, 0.2f, 0);
this.GetComponent<AudioSource>().Play();
}
}