10
2015
Simple Event & Delegate Script

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
Related Posts
4 Comments + Add Comment
Leave a comment
Recent posts
- Adding Real World Location to Ice Fishing Prototype
- [web tool] Image Channel Inspector : AlphaScope
- Editor Tool: Smart Recompile (don’t recompile if edit comments)
- Editor Tool: Scene Size Analyzer
- LudumDare 60: Old Tech
- uBasic Scripting Language for Unity
- GreaseMonkey+Editor Plugin: 1-Click Copy script from ChatGPT (Web) to Unity Editor (as script)
- Editor Tool: Property Watcher
- .unityignore : Hide files from Project window
- PostBuild Script to Create Single exe Standalone File
- Game Loop Designer
- Favorites in PackageManager
Recent Comments
Coin:
CUgDSbRqFcAumDSAcdKDvuXsw26VdkJe8C8WGUQHBAGS
An article by












How to use Delegates in Unity:
http://unitydojo.blogspot.fi/2015/03/how-to-use-delegates-in-unity-like-boss.html
C# Events and Delegates Made Simple
using UnityEngine.Events, UnityEvent:
http://forum.unity3d.com/threads/unityevent-where-have-you-been-all-my-life.321103/
Delegates and Events in Unity
http://www.unitygeek.com/delegates-events-unity/