Created
September 4, 2014 06:16
-
-
Save stramit/76e53efd67a2e1cf3d2f to your computer and use it in GitHub Desktop.
Sending Custom Events via the EvenSystem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!