Search Unity

How to access UI button transitions events?

Discussion in 'Scripting' started by Delcasda, Apr 19, 2021.

  1. Delcasda

    Delcasda

    Joined:
    Mar 3, 2013
    Posts:
    27
    Hi, I want to play a sound when the mouse is over a button and a different one when the user actually clicks the button but the sound for "over" keeps playing when I click the button too. I am implementing the interfaces IPointerEnterHandler and IPointerExitHandler trying to filter the behaviour but the "exit" event is triggered when the mouse is up too, so when I try to click the "enter" event trigger the over sound again . What I need is something similar to what standard button class do to manage Highlighted and Press transitions. Is there a way to listen to transitions events?
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Events;
    5. using UnityEngine.EventSystems;
    6. using UnityEngine.UI;
    7.  
    8. public class ButtonSounds : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
    9.  
    10. {
    11.     public AudioSource audioso;
    12.     public AudioClip overAudio;
    13.     public AudioClip clickAudio;
    14.  
    15.     bool playsound = true;
    16.  
    17.     public void OnSelect(BaseEventData eventData)
    18.      {
    19.         Debug.Log("select " + this.name);
    20.         if (playsound) audioso.PlayOneShot(clickAudio);
    21.      
    22.  
    23.      }
    24.  
    25.     public void OnPointerEnter(PointerEventData eventData)
    26.     {      
    27.         Debug.Log("Enter "+this.name);
    28.        if(playsound) audioso.PlayOneShot(overAudio);
    29.         playsound = false;
    30.  
    31.     }      
    32.  
    33.     public void OnPointerExit(PointerEventData eventData)
    34.     {
    35.         Debug.Log("Exit " + this.name);
    36.         playsound = true;
    37.     }
    38.  
    39.  
    40. }