- Home /
Toggle onPointerDown event
Note: This is a duplicated question from StackOverflow: http://stackoverflow.com/questions/29669717/unity-toggle-onpointerdown-event
I'm trying to trigger an event when a toggle is being clicked. onValueChanged
does not work for me because it's causing an infinite loop of events.
That's what I have now (simplified):
toggle.onValueChanged.AddListener (delegate {
myMethod();
});
That's what I'd love to have (but I don't):
toggle.onPointerDown.AddListener (delegate {
myMethod();
});
I'm new to Unity and having some problems to understand how events work. I've been researching, but I don't event understand why onPointerDown should be different to use than onValueChanged.
to avoid an infinite loop of events, have a bool flag in your class. set this bool depending on where the my$$anonymous$$ethod is called from and check the state of the bool inside the my$$anonymous$$ethod to avoid an infinite loop.
I suspect the cause of the infinite loop is inside my$$anonymous$$ethod. Can you post that.
Hi, I actually solved my problem with a flag some days ago. Anyway I left the question open for someone to ask how to trigger that onPointerDown event, I'm still curious and someone could need that answer too.
Effectively "my$$anonymous$$ethod" was causing the infinite loop, long story short: there I was changing the value of another toggle so my$$anonymous$$ethod was being called again. I already knew that at the time and was trying to avoid that loop.
I'm not sure I understand the question. It would be better to mark this question as answered and open a new question.
Answer by lordlycastle · Apr 24, 2015 at 01:17 PM
I have never used delegate, I find those confusing in C#. However, you can do this:
toggle.OnClick.AddListener(() => MyMethod(argument));
Read here about the lambda syntax (=>)
Answer by Paul-Sinnett · Apr 24, 2015 at 02:24 PM
I see. Well, you could add your own event trigger to the toggle button:
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
public class PointerDownTrigger : MonoBehaviour, IPointerDownHandler
{
public EventTrigger.TriggerEvent onPointerDown;
public void OnPointerDown(PointerEventData eventData)
{
onPointerDown.Invoke(eventData);
}
}
Now you should be able to use your code:
public class ToggleClick : MonoBehaviour
{
public PointerDownTrigger toggle;
void myFunction()
{
Debug.Log("Pointer down!");
}
void Start()
{
toggle.onPointerDown.AddListener(delegate { myFunction(); });
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613193247im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
how to know sender of triggerenter event? 1 Answer
Collision not triggered by box collider 2 Answers
Event throwing null reference exception in OnTriggerEnter 0 Answers
How to enable the box collider tick box on a trigger event 2 Answers
Passing sender object as an argument in AddListener method 1 Answer