Skip to content

Suggestion: event detectors #8

Description

@paulmasri

Within my own code, I have created an event detector script for each event type. See code below.

@lisandroct I propose moving it into this repo instead and build it into the code generator. I am happy to do this and raise a PR and I'd welcome any comments before I get started.

The event detector script has a public OnEventRaised() method. In my scene, I add a game object and add scripts XxxxListener and the corresponding XxxxDetector. I drag a specific event asset into the listener and set the response to OnEventRaised() of the detector. During runtime, whenever that event is raised, OnEventRaised() gets called and does a Debug.Log() identifying the event and its arguments.

EventDetector.cs

using UnityEngine;

namespace PaulMasriStone.EventSystem
{
	public class EventDetector : MonoBehaviour
	{
		public void OnEventRaised()
		{
			Debug.Log($"Raised {gameObject.name}");
		}
	}
}

EventDetectors.cs

using System.Collections;
using UnityEngine;

namespace PaulMasriStone.EventSystem
{
	public abstract class EventDetector<T> : MonoBehaviour
	{
		public void OnEventRaised(T arg1)
		{
			Debug.Log($"Raised {gameObject.name} with {arg1}");
		}
	}

	public abstract class EventDetector<T, U> : MonoBehaviour
	{
		public void OnEventRaised(T arg1, U arg2)
		{
			Debug.Log($"Raised {gameObject.name} with {arg1},{arg2}");
		}
	}

	public abstract class EventDetector<T, U, V> : MonoBehaviour
	{
		public void OnEventRaised(T arg1, U arg2, V arg3)
		{
			Debug.Log($"Raised {gameObject.name} with {arg1},{arg2},{arg3}");
		}
	}

	public abstract class EventDetector<T, U, V, W> : MonoBehaviour
	{
		public void OnEventRaised(T arg1, U arg2, V arg3, W arg4)
		{
			Debug.Log($"Raised {gameObject.name} with {arg1},{arg2},{arg3},{arg4}");
		}
	}
}

FloatDetector.cs

namespace PaulMasriStone.EventSystem
{    
    public class FloatDetector : PaulMasriStone.EventSystem.EventDetector<float>
    {}
}

Example in Unity

Screenshot of Unity showing the event asset and event detector game object

Screenshot Unity during runtime – on raising a float event, the event is logged to the console

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions