Unity3D——SendMessage方法的使用
SendMessage效率不高,因为每次调用的时候都会去遍历检测自身或者子节点上要调用的方法。
一、方法
GameObject自身的Script
SendMessage("函数名", 参数,SendMessageOptions)
自身和子Object的Script
BroadcastMessage("函数名", 参数,SendMessageOptions)
自身和父Object的Script
SendMessageUpwards("函数名", 参数,SendMessageOptions)
SendMessageUpwards("函数名", 参数,SendMessageOptions)
可以跨语言的,例如Javascript可以调用C#的函数
二、第三个参数使用
如果没有找到相应函数,会报错(默认是这个状态)
SendMessageOptions.RequireReceiver
SendMessageOptions.RequireReceiver
没有找到相应函数,也不会报错,自动忽略
SendMessageOptions.DontRequireReceiver
三、测试代码
- using UnityEngine;
- using System.Collections;
- public class TestSendMassage : MonoBehaviour {
- void Start () {
- //this.gameObject.BroadcastMessage("sendMsg", SendMessageOptions.DontRequireReceiver);
- //this.gameObject.SendMessageUpwards("sendMsg", SendMessageOptions.DontRequireReceiver);
- this.gameObject.SendMessage("sendMsg", SendMessageOptions.DontRequireReceiver);
- }
- // Update is called once per frame
- void sendMsg() {
- Debug.Log("sendMsg");
- }
- }
- using UnityEngine;
- using System.Collections;
- //该脚本依次挂载在TestSendMassage脚本所挂节点的父节点或者子节点上
- public class TestMsg : MonoBehaviour {
- void sendMsg()
- {
- Debug.Log("sendMsg1");
- }
- }