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 myMethod is called from and check the state of the bool inside the myMethod to avoid an infinite loop.

–

I suspect the cause of the infinite loop is inside myMethod. 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 "myMethod" was causing the infinite loop, long story short: there I was changing the value of another toggle so myMethod 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.

–

2 Answers

2

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 (=>)

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(); });
    }
}