Jan
10
2015

Simple Event & Delegate Script

events_delegates

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
listener_events
– 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


4 Comments + Add Comment

Leave a comment

Connect

Twitter View LinkedIn profile Youtube Youtube Join Discord Twitch

UnityLauncherPro

Get UnityLauncherPRO and work faster with Unity Projects!
*free unity hub alternative

@unitycoder_com

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.