无参数的事件委托,继承ScriptableObject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName ="Data/EventChannels/VoidEventChannel",fileName ="VoidEventChannel_")]
public class VoidEnentChannel : ScriptableObject
{
event System.Action Delegate;
//启动所有委托
public void Broadcast()
{
Delegate?.Invoke();
}
//增加事件
public void AddListener(System.Action action)
{
Delegate += action;
}
//移除事件
public void RemoveListener(System.Action action)
{
Delegate -= action;
}
}
使用方法,列如主角触发机关,会发生的一系列事情
这里的主角碰撞机关,播放广播,通知所有订阅者
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GateTrigger : MonoBehaviour
{
[SerializeField] AudioClip pickUpSFX;
[SerializeField] ParticleSystem pickUpVFX;
[SerializeField] VoidEnentChannel gateTriggeredEventChannel;
// public event System.Action Delegate;//System.Action 委托方法 event事件 用+=来订阅事件
private void OnTriggerEnter(Collider other)
{
if(other.TryGetComponent<PlayerController>(out PlayerController plaer))
{
// Delegate?.Invoke();//非空就运行 Invoke在拥有此控件的基础窗口句柄的线程上执行指定的委托。
gateTriggeredEventChannel.Broadcast();//播放广播 调用委托中的所有事件
SoundEffectPlay.audioScourc.PlayOneShot(pickUpSFX);
Instantiate(pickUpVFX,transform.position,Quaternion.identity);
Destroy(gameObject);
}
}
}
其他物体注册订阅,根据广播做出反应
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gate : MonoBehaviour
{
[SerializeField] VoidEnentChannel gateTriggeredEventChannel;
private void OnEnable()
{
gateTriggeredEventChannel.AddListener(OnPen);
}
private void OnDisable()
{
gateTriggeredEventChannel.RemoveListener(OnPen);
}
void OnPen()
{
Destroy(gameObject);
}
}
可以根据情况使用委托
也可以传递参数
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OnePartEnentchannel<T> : ScriptableObject
{
event System.Action<T> Delegate;
//启动所有委托
public void Broadcast(T obj)
{
Delegate?.Invoke(obj);
}
//增加事件
public void AddListener(System.Action<T> action)
{
Delegate += action;
}
//移除事件
public void RemoveListener(System.Action<T> action)
{
Delegate -= action;
}
}