Just a quick test on events & delegates (taken from this live tutorial)
– New scene
– Add Sphere object to the scene (and move it into Main Camera view, for example 0,0,0)
– Create new script: FireEvent.cs
using UnityEngine; using System.Collections; public class FireEvent : MonoBehaviour { public delegate void Clicked(); public event Clicked WasClicked; void OnMouseDown() { if (WasClicked!=null) // we have someone listening { Debug.Log("We have a listener, send event"); WasClicked(); }else{ Debug.Log("Nobody is listening!!!! noooooo"); } } }
– Attach “FireEvent.cs” script into Sphere gameobject
– Create new script: Listener.cs
using UnityEngine; using System.Collections; public class Listener : MonoBehaviour { public GameObject EventManager; // reference to event firing object void Start() { // subscribe to the event (attach listener) EventManager.GetComponent<FireEvent>().WasClicked+=SomethingWasClickedOutside; // call this function if event is fired } void SomethingWasClickedOutside() { Debug.Log ("Listener.cs: Event was fired!"); } }
– Create new Empty Gameobject
– Attach “Listener.cs” to that empty gameobject
– Assign Sphere into the “EventManager” field in the inspector
– Hit play and then click the Sphere with mouse, event should be fired.
More info:
http://unity3d.com/learn/tutorials/modules/intermediate/scripting/events
http://unity3d.com/learn/tutorials/modules/intermediate/scripting/delegates