kingBook

导航

C# 事件event

public class AAA: MonoBehaviour {

    public delegate void PlayEndDelegate();
    //此处可以使用内置的Action或Func委托简化,
    //具体参考 https://www.cnblogs.com/kingBook/p/5383415.html
    public event PlayEndDelegate playEndEvent;

    private void playEndHandler(){
        playEndEvent();
        //判断是否为null
        //if(playEndEvent!=null)playEndEvent();
        //判断是否为null,还可以简化
        //playEndEvent?.Invoke();
    }

}
public class BBB: MonoBehaviour {
    private AAA _aaa;
    void Start () {
        _aaa=new AAA();
        _aaa.playEndEvent+=onPlayEndHandler;//添加侦听
        _aaa.playEndHandler();
    }

    private void onPlayEndHandler(){
        Debug.Log("bbb onPlayEndHandler");
    }
    
    void OnDestroy(){
        _aaa.playEndEvent-=playEndHandler;//移除侦听
    }
}
//output: bbb onPlayEndHandler

posted on 2019-06-28 12:10  kingBook  阅读(968)  评论(0编辑  收藏  举报