using UnityEngine;
using System.Collections;
public class EventManager : MonoBehaviour
{
// This line is defining a type alias called ClickAction. A ClickAction is a
// function that takes in no arguments and has a return type of void. Any function
// that matches this signature is a ClickAction
public delegate void ClickAction();
// This line is declaring an event in a static variable. You can think of an event
// as being like a list of callback functions. These callback functions must have
// type ClickAction
public static event ClickAction OnClicked;
void OnGUI()
{
if(GUI.Button(new Rect(Screen.width / 2 - 50, 5, 100, 30), "Click"))
{
// This if statement checks whether or not there are any callback functions
// registered with the OnClick event.
if(OnClicked != null)
// Here we call the OnClick event. Internally, C# goes through the list of
// callback functions and invokes them one at a time
OnClicked();
}
}
}
public class TeleportScript : MonoBehaviour
{
void OnEnable()
{
// This line will add a callback to the OnClick event that we defined previously
EventManager.OnClicked += Teleport;
}
void OnDisable()
{
// This line will remove the callback when the GameObject is disabled or destroyed
EventManager.OnClicked -= Teleport;
}
// This method is a ClickAction since it takes no parameters and has a void return type
void Teleport()
{
// This method will be invoked by the EventManager since we added this method
// as a callback in the OnEnable method
// Do the teleportation
Vector3 pos = transform.position;
pos.y = Random.Range(1.0f, 3.0f);
transform.position = pos;
}
}
public class TurnColorScript : MonoBehaviour
{
void OnEnable()
{
// This line will add a callback to the OnClick event that we defined previously
EventManager.OnClicked += TurnColor;
}
void OnDisable()
{
// This line will remove the callback when the GameObject is disabled or destroyed
EventManager.OnClicked -= TurnColor;
}
// This method is a ClickAction since it takes no parameters and has a void return type
void TurnColor()
{
// This method will be invoked by the EventManager since we added this method
// as a callback in the OnEnable method
// Change the color
Color col = new Color(Random.value, Random.value, Random.value);
renderer.material.color = col;
}
}