Reputation: 109
im making a game and want to code a event function. Example:
public void OnEvent(string args[]) {}
This function should be accessable through every script, like the Start() or Update() 'event' that you just need to call as function to be registered.
Any ideas?
Upvotes: 3
Views: 7243
Reputation: 4591
Unity Events
Unity has a set of delegates, UnityAction, that have generic versions that accept up to 16 params.
Unity also has a set of events, UnityEvent, that also have generic versions with up to 16 params.
Unity events are used in the UI system for linking events (such as On Click of Button) to an action (a function in a script). These can be saved with the scene and are editable from the inspector, unlike the vanilla C# events and delegates.
These are both found in the UnityEngine.Events
namespace.
Event Class example
private UnityEvent<string[]> myEvent = new UnityEvent<string[]>();
public void RegisterForEvent(UnityAction<string[]> action)
{
myEvent.AddListener(action); // register action to receive the event callback
}
public void UnregisterEvent(UnityAction<string[]> action)
{
myEvent.RemoveListener(myAction); // unregister to stop receiving the event callback
}
private void RaiseEvent()
{
myEvent.Invoke(new string[] { "Hello", "World" }); // raise the event for all listeners
}
Some Other Class example
private UnityAction<string[]> myAction
private void OnEnable()
{
// Create the action if it doesn't already exist
//
if (myAction == null)
myAction = new UnityAction<string[]>(EventCallback);
// Register to the event
//
otherScript.RegisterForEvent(myAction);
}
private void OnDisable()
{
// Unregister from the event when this object is disabled or destroyed
//
otherScript.UnregisterEvent(myAction);
}
private void EventCallback(string[] values)
{
Debug.Log("My action was called!");
}
Alternatively..
This can be accomplished with the event
and delegate
keywords. You create a delegate which is the method signature for the callback, and define an event that uses this delegate. Methods register to the event using +=
and unregister from the event using -=
. Events Programming Guide for C#
You want to make sure to utilize OnEnable
and OnDisable
for registering/unregistering events in Unity, regardless of which route you decide to take.
Upvotes: 3