初学C#记录委托和事件
场景:首领A要搞一场鸿门宴,吩咐部下B和C各自带队埋伏在屏风两侧,约定以杯为令:若左手举杯,则B带队杀出;若右手举杯,则C带队杀出;若直接摔杯,则B和C同时杀出。B和C袭击的具体方法,首领A并不关心。
以下脚本直接挂在一个空对象上就可以运行了物体上
首领A类:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public delegate void RaiseEventHandler(string Hand);
public delegate void FallEventHandler();
public class HeadA : MonoBehaviour
{
public static event RaiseEventHandler _RaiseEvent;
public static event FallEventHandler _FallEvent;
public void Raise(string Hand)
{
Debug.Log("首领A+{0}"+Hand+"举杯");
if (_RaiseEvent!=null)
{
_RaiseEvent(Hand);
}
}
public void Fall()
{
Debug.Log("首领a摔杯");
if (_FallEvent != null)
_FallEvent();
}
private void OnGUI()
{
if(GUILayout.Button("举左手"))
{
Raise("左");
}
if (GUILayout.Button("举右手"))
{
Raise("右");
}
if (GUILayout.Button("摔杯子"))
{
Fall();
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoldierC :MonoBehaviour
{
public void Attack()
{
Debug.Log("SoldierC攻击");
}
private void Start()
{
HeadA._RaiseEvent += new RaiseEventHandler(RaiseEvent);
HeadA._FallEvent += new FallEventHandler(Attack);
}
private void RaiseEvent(string Hand)
{
if (Hand.Equals("右"))
{
Attack();
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoldierB :MonoBehaviour {
public void Attack()
{
Debug.Log("SoldierB攻击");
}
private void Start()
{
HeadA._RaiseEvent += new RaiseEventHandler(RaiseEvent);
HeadA._FallEvent += new FallEventHandler(FallEvent);
}
private void FallEvent()
{
Attack();
}
private void RaiseEvent(string Hand)
{
if (Hand.Equals("左"))
{
Attack();
}
}
}