public void SendMessage (string methodName, object value= null, SendMessageOptions options= SendMessageOptions.RequireReceiver);

参数

methodName要调用的方法的名称。
value要传入已调用方法的可选参数值。
options如果目标对象上不存在该方法,是否应报错?

描述

调用此游戏对象中的每个 MonoBehaviour 上名为 methodName 的方法。

通过使用零参数,该接收方法可选择忽略此参数。 如果选项设置为 SendMessageOptions.RequireReceiver,则在任何组件均未拾取此消息时输出错误。

注意,不会将消息发送到非活动对象(即,在 Editor 中或使用 SetActive 函数已停用的对象)。

using UnityEngine;

public class Example : MonoBehaviour { void Start() { // Calls the function ApplyDamage with a value of 5 // Every script attached to the game object // that has an ApplyDamage function will be called. gameObject.SendMessage("ApplyDamage", 5.0); } }

public class Example2 : MonoBehaviour { public void ApplyDamage(float damage) { print(damage); } }