1. Events can only be defined inside a class, while delegates can be defined inside or outside a class. Event definitions report errors externally
2. Delegates and events can be called indirectly in other classes. However, in an external class, the delegate can = a method, while the event cannot, only + = a method. Events can only be triggered inside the defined class, while delegates can be triggered in other external class calls.
using UnityEngine;
using System.Collections;
using System;
public delegate void OnClickHandler();
public class MyDelateStudy : MonoBehaviour {
public OnClickHandler OnClickDelate;
public event OnClickHandler OnClickEvent;
private void Awake()
{
OnClickDelate += OnClickDelateFun;
OnClickEvent+= OnClickEventFun;
}
private void OnDestroy()
{
}
private void OnClickDelateFun()
{
Debug .Log ("MyDelateStudy----OnClickFunDelateFun implement");
}
private void OnClickEventFun()
{
Debug.Log("MyDelateStudy----OnClickFunEventFun implement");
}
private void Update()
{
if(Input.GetKeyDown (KeyCode.D))
{
if(OnClickDelate !=null )
OnClickDelate();
}
if(Input .GetKeyDown (KeyCode.E ))
{
if(OnClickEvent !=null )
{
OnClickEvent();
}
}
}
}
In mydeletestudy.cs, both the delegate onclickdelete and the event OnClickEvent can be monitored by + = a method in another class mydeletestudy2.
using UnityEngine;
using System.Collections;
using System;
public class MyDelateStudy2 : MonoBehaviour {
MyDelateStudy my1;
void Start ()
{
my1 = GetComponent<MyDelateStudy>();
my1.OnClickDelate += OnClickFunDelateFun;
my1.OnClickEvent += OnClickEventFun;
}
private void OnClickFunDelateFun()
{
Debug.Log("MyDelateStudy2---OnClickFunDelate fun implement");
}
private void OnClickEventFun()
{
Debug.Log("MyDelateStudy2----OnClickFunEventFun implement");
}
// Update is called once per frame
void Update ()
{
}
}
A. But the event cannot be sufficient in the external class = a method, which can be used in the class defining the event
B. Events can only be triggered inside the defined class, while delegates can be triggered in other external class calls.