初学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();

        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值