- Home /
UI 4.6 add pointer enter event to button, c# (Not using Editor)
How do I add an event listener to a button created in code for mouse over events etc.
I have previously added onclick events using
animationButton.onClick.AddListener(delegate {buttonClicked();});
public void buttonClicked(){
print("Clicked");
}
However there is no similar .onHover member etc. So how do I add an event for this?
Thanks,
Answer by InvincibleCat · Feb 13, 2015 at 11:17 PM
Your class should inherit of IPointerEnterHandler (you have different other events)
Don't forget using UnityEngine.EventSystems;
I assume that animationButton.onClick.AddListener(delegate {buttonClicked();});
is in your Start or Awake method ?
And try that way
animationButton.onClick.AddListener(buttonClicked);
Thanks, I ended up using this code:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class PointerEventsController : $$anonymous$$onoBehaviour,IPointerEnterHandler, IPointerExitHandler {
public int mouseOnCount = 0;
private AudioClip audioclip;
private AudioSource audiosource;
public void Start(){
audioclip = Resources.Load <AudioClip> ("button_hover_sound");
gameObject.AddComponent<AudioSource> ();
audiosource = gameObject.GetComponent<AudioSource> ();
}
public void OnPointerEnter(PointerEventData eventData)
{
mouseOnCount = mouseOnCount+1;
Debug.Log(mouseOnCount);
audio.PlayOneShot (audioclip);
}
public void OnPointerExit(PointerEventData eventData)
{
}
}
I just find it strange that the .onclick parameter exists for clicking but not for other events.
you can still use EventTrigger component if you want by the way.
There is not something like onClick for each events only because with a button you will ALWAYS have something happening onClick but not true for the other ones. So it is memory consu$$anonymous$$g to have useless stuff.
I also think that the interface allow you to spread your events easily in your hierarchy
Your answer
![](https://koobas.hobune.stream/wayback/20220613183245im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Issues when hooking GUI to code 0 Answers
Noob question to classes 1 Answer