Skip to content

Instantly share code, notes, and snippets.

@stramit
Created September 4, 2014 06:16
Show Gist options
  • Save stramit/76e53efd67a2e1cf3d2f to your computer and use it in GitHub Desktop.
Save stramit/76e53efd67a2e1cf3d2f to your computer and use it in GitHub Desktop.
Sending Custom Events via the EvenSystem
using System;
using System.Collections.Generic;
using UnityEngine.Events;
// interface you implement in your MB to receive events
public interface ICustomHandler : IEventSystemHandler
{
void OnCustomCode(CustomEventData eventData);
}
// Custom data we will send via the event system
public class CustomEventData : BaseEventData
{
public string m_CustomData;
public CustomEventData(EventSystem eventSystem, string customData)
: base(eventSystem)
{
m_CustomData = customData;
}
}
// container class that holds the execution logic
// called by the event system to delecate the call to
// the intercea
public static class MyCustomEvents
{
// call that does the mapping
private static void Execute(ICustomHandler handler, BaseEventData eventData)
{
// The ValidateEventData makes sure the passed event data is of the correct type
handler.OnCustomCode (ExecuteEvents.ValidateEventData<CustomEventData> (eventData));
}
// helper to return the functor that should be invoked
public static ExecuteEvents.EventFunction<ICustomHandler> customEventHandler
{
get { return Execute; }
}
}
//Custom input module that can send the events
public class MyInputModule : BaseInputModule
{
// list of objects to invoke on
public GameObject[] m_TargetObjects;
// called each tick on active input module
public override void Process()
{
// if we don't have targets return
if (m_TargetObjects == null || m_TargetObjects.Length == 0)
return;
// for each target invoke our custom event
foreach (var target in m_TargetObjects)
ExecuteEvents.Execute (target, new CustomEventData (eventSystem, "Custom Data"), MyCustomEvents.customEventHandler);
}
}
// Class that implements the Handler
public class MyCustomMB : MonoBehaviour, ICustomHandler
{
public void OnCustomCode(CustomEventData eventData)
{
Debug.Log (eventData.m_CustomData);
}
}
@MrFJ
Copy link

MrFJ commented Sep 27, 2017

Thanks, this helped a lot! Look for "3D EventTrigger", or whatever I decide to call it, on the asset store (probably free) in a few weeks!
image

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment