How do I play a sound while holding pressed on a UI button?

How do I make a button play a sound while being pressed and have it stop while NOT being pressed?

This is my current script for it.

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class PlaySound : MonoBehaviour
{

    public AudioSource soundPlayer;
    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
       
    }

    public void playThisSoundEffect()
    {
          soundPlayer.Play();
    }
}

There are various forms, but some of the easiest involve OnKeyDown and OnKeyUp if its via code. Or if it is a UI button, you could create an event trigger and then basically do the same thing: PointerUp or PointerDown

Then you assign the script and function to the event trigger: 9789354--1404816--upload_2024-4-23_15-46-22.png

Note, to avoid confusion for this basic example, remove the Button component and just use the Event Trigger.

2 Likes

It works perfectly. Thank you sooo much.

1 Like