当前位置:网站首页>Unity中事件的3种实现方法
Unity中事件的3种实现方法
2022-08-02 14:12:00 【夏湾】
Unity中事件的3种实现方法
前言
假设有两个脚本A和脚本B,当A调用某一函数fn时,要发布事件,而监听A中事件的脚本B,要做出对应回应。对此有三种方法,
UnityEvent:有UI界面,不需要手动取消监听
event:物体被被摧毁时要手动取消监听或阻止函数继续运行
BroadcastMessage:方便于自身传递,但无法广播到被禁用的组件或被禁用物体上的
UnityEvent
UnityEvent持有对象的引用,当对象被销毁时就不会再调用对应函数了。类似于
if(obj != null) { obj.fn(…); }
//脚本A
using UnityEngine.Events;
public UnityEvent<...> attacked = new UnityEvent<...>();
public void fn() {
attacked(...); }

event
//... 表示参数或参数类型,如Action,Action<GameObject>,Action<GameObject,int>等
//这里假设都挂有A组件,一般情况下需要判空
//脚本A
public event System.Action<...> attacked;
public void fn() {
attacked(...); }
//脚本B
void Start(){
GetComponent<A>().attacked += OnAttacked;
otherObj.GetComponent<A>().attacked += OnAttacked;
}
void OnAttacked(...) {
//do something
print(gameObject.name);
}
void OnDestroyed(){
//监听听自身的可忽略,除非有调用Object.Destroy(GetComponent(B)())
//GetComponent<A>().attacked-= OnAttacked;
//监听其他物体的不可忽略,因为当B组件被销毁时,
//其他物体上的A组件还会调用B中的函数,所以要取消
otherObj.GetComponent<A>().attacked-= OnAttacked;
}
BroadcastMessage
BroadcastMessage向自身及子物体上所以“非禁用”脚本广播。
当物体被禁用(gameObject.SetActive(false))时,
其身上所以脚本和子物体上所以脚本都相当于“禁用”,就无法接受到广播。
public void BroadcastMessage(string methodName,
object parameter = null,
SendMessageOptions options = SendMessageOptions.RequireReceiver);
最后一个参数默认是有要求接收,如果没用接收就会报错。
如果不希望报错可以改为,SendMessageOptions.DontRequireReceiver
切换场景时static的注意事项
当切换场景时,没用调用过DontDestroyOnLoad()的GameObject及其脚本会被销毁,但是那些脚本上的static变量并不会消失。如:
//脚本A
static int v1; //不变
static float v1; //不变
static GameObject obj; //obj被销毁,在使用前要判空 if(obj!=null) 或 if(obj)
static event System.Action action; //保存的事件还在,可以用 action=null 来清空监听
边栏推荐
- 4.发布帖子,评论帖子
- Based on the matrix calculation in the linear regression equation of the coefficient estimates
- 开心一下,9/28名场面合集
- MATLAB制作简易小动画入门详解
- [System Design and Implementation] Flink-based distracted driving prediction and data analysis system
- 计算机导论——数据库
- 剑指offer:合并两个排序的链表
- 二叉排序树与 set、map
- mysql的索引结构为什么选用B+树?
- MATLAB绘图函数plot详解
猜你喜欢
随机推荐
队列与栈
What are IPV4 and IPV6?
质数相关问题-小记
word方框怎么打勾?
剑指offer:删除链表中重复的节点
Open the door of power and electricity "Circuit" (2): Power Calculation and Judgment
第二十九章:树的基本概念和性质
关于推荐系统的随想
pygame image rotate continuously
Exotic curiosity-a solution looking - bit operations
关于混淆的问题
Open the door to electricity "Circuit" (3): Talk about different resistance and conductance
Summarize computer network super comprehensive test questions
企业的电子签名、私钥签名
Unity-Ads广告插件
总结计算机网络超全面试题
MATLAB绘图函数plot详解
LeetCode 2353. 设计食物评分系统 维护哈希表+set
Mysql的锁
Open the door of electricity "Circuit" (1): voltage, current, reference direction








