Generic method trigger useful for scripted events/prototyping

Monday, January 4, 2016 3:38 PM

I needed a generic method trigger at some point, I remember having a hard time finding out how to do it. I use this a lot for different things, I thought I could share. I don't remember who did this first, I'm bad at this :

 

using System;

using UnityEngine;

using UnityEngine.Events;

using UnityEngine.EventSystems;

using UnityEngine.Serialization;

public class GenericMethodTrigger : MonoBehaviour, IEventSystemHandler
{
    
    public bool triggerOnce = false;
    public bool triggered = false;

    [SerializeField]
    private AfterTrigger afterTrigger = new AfterTrigger();
    
    public void OnTriggerEnter2D(Collider2D collision)
    {
        if (!triggered)
        {
            afterTrigger.Invoke();
            if (triggerOnce) { triggered = true; }
        }
    }

    [Serializable]
    public class AfterTrigger : UnityEvent
    { }

}

 

Using a collider with this as a trigger, you can trigger any method from any other object. It's useful for prototyping or to trigger scripted events ot things like that. 

Discussion

Leave a reply

Name ( required )
E-mail ( required, won't be published )
Wesite