- . 组件方法:用于对象自身脚本之间、父级对子级、子级对父级的通信;不适合游戏对象之间的数据通信;
- 1. Component.SendMessage
- . 游戏对象挂载的所有组件中即兄弟脚本,只要定义了该方法都会执行;
- . Every script attached to the game object that has a xxx function will be called.
- 2. Component.BroadcastMessage
- . 向兄弟脚本,同时 向子对象脚本发送;
- . Every script attached to the game object and all its children that has a xxx function will be called.
- 3. Component.SendMessageUpwards
- . 向兄弟脚本,同时 向父级对象脚本、祖先对象脚本发送;
- . Every script attached to this game object and any ancestor that has a xxx function will be called.
- . 更多使用细节,请查阅API;
- []SendMessage的使用
- 1. 创建一个游戏对象,分别挂载3个脚本:A.cs、B.cs、C.cs;
- 2. 脚本A:每次按下鼠标左键,就发送消息;脚本B、C接收消息并执行指定的函数;
- 3. 运行游戏,查看函数的调用情况;
- 4. 如果A也有greeting函数,它也会执行:自己发给自己;
-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class A : MonoBehaviour
{
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
SendMessage("greeting","Cnplaman");
}
}
}
-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class B : MonoBehaviour
{
void greeting(string str)
{
print(str + " B, hi,there.");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class C : MonoBehaviour
{
void greeting(string str)
{
print(str + " C, hi,there.");
}
}
- []BroadcastMessage的使用
- 1. 创建一个游戏对象GM,挂载脚本GM.cs向3个子对象发送消息;
- 2. 创建3个子对象a、b、c,分别挂载3个脚本:A.cs、B.cs、C.cs;每个脚本都定义了消息接受函数;
- 3. 运行游戏,查看消息的发送情况:每个子对象都执行函数;
-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GM : MonoBehaviour
{
void Start()
{
BroadcastMessage("greeting","broadMsg");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class A : MonoBehaviour
{
void greeting(string str)
{
print(str + " A, hi,there.");
}
}
-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class B : MonoBehaviour
{
void greeting(string str)
{
print(str + " B, hi,there.");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class C : MonoBehaviour
{
void greeting(string str)
{
print(str + " C, hi,there.");
}
}
- 4. 如果将GM.cs的BroadcastMessage换成SendMessage,则会提示发送失败:无同级组件;也可以指定发送选项为不需要接受者DontRequireReceiver;
-
- 5. 如果在GM.cs也定义了消息接受函数,或者游戏对象GM又挂载了其它也定义了消息接受函数的脚本,则这些同级脚本和子对象脚本都会执行函数;