- Home /
How to play loop an audio clip on button hold down?
Hey guys im really new in what comes to Unity. I'm trying to make some drum pads to have individual sound that when you press and hold it it will loop. So far i got to this script but i can't make it work individually for each button. Instead when i add it to a button whenever i click in the screen it will play it. Any idea of what should i do?
using UnityEngine; using System.Collections;
public class playSound : MonoBehaviour {
public AudioSource mySound;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.Mouse0))
{
mySound.enabled = true;
mySound.loop = true;
}
else
{
mySound.enabled = false;
mySound.loop = false;
}
}
}
Answer by HenryStrattonFW · Jan 29, 2017 at 02:24 PM
This is because you are testing Input.GetKey which will just make a query to the input manager to see if the mouse was pressed. It will respond regardless of if the mouse was over your button at the time.
I'm not sure what you are using for your buttons, but if you are using the unity gui (uGUI) then perhaps you want to look at using the OnPointerDown and OnPointerUp methods: https://docs.unity3d.com/ScriptReference/UI.Selectable.OnPointerDown.html https://docs.unity3d.com/ScriptReference/UI.Selectable.OnPointerUp.html
Can't say I've used the unity GUI or event system much but from the documentation it looks like these methods would provide the necessary functionality.
Hope this is of some help.