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
- LudumDare59 : Signal
- Unity Editor: Tree Generator
- Leaf/Foliage Generator Tools (Runs in Browser)
- Testing Unity AI Beta
- Ways to Support UnityCoder Development
- Using UI Slider to Create 5-Star Rating Element
- Game Music Library For Unity (editor plugin)
- Fontastic : Easily Test Fonts in Unity Editor!
- GeoTiff Importer & Terrain Generator for Unity
- Create Baked DropShadow for UI images
- .JP2 Ortho Image Converter to PNG/JPG/TIFF
- Convert LAS/LAZ/PLY pointclouds to GLTF (GLB) Point Meshes (standalone converter)
Recent Comments
- on Mesh Exploder (sources)
- on Sprite Sheet Flip Book Shader
- on Sprite Sheet Flip Book Shader
- on [Asset Store] PolygonCollider2D Optimizer
- on Trajectory Test Scene 2.0
- on Vector3 maths for dummies!
- on UnityHub 3.6.0: Remove Version Control & Cloud Dashboard columns
- on Using RenderDoc with Unity (graphics debugger)
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/