unity跨脚本传递参数(1)SendMessage

参照unity2019.3文档中给出的对SendMessage给出的解释:
原版:Calls the method named methodName on every MonoBehaviour in this game object.
The receiving method can choose to ignore the argument by having zero parameters. If options is set to SendMessageOptions.RequireReceiver an error is printed if the message is not picked up by any component.
Note that messages will not be sent to inactive objects (ie, those that have been deactivated in the editor or with the SetActive function).

翻译版:调用此游戏对象中methodName每个MonoBehaviour上命名的方法。

接收方法可以选择具有零个参数来忽略该参数。如果将选项设置为SendMessageOptions.RequireReceiver,并且任何组件都未接收到该消息,则会显示错误消息。请注意,消息将不会发送到非活动对象(即,已在编辑器中或通过SetActive函数取消激活的对象)。

SendMessage`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);
    }
}`

在这里插入图片描述
即第一个参数是要传递消息的方法名,第二个参数是被传方法中需要的参数,第三个是选择需不需要有返回值。

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ShowAllChoice : MonoBehaviour
{
    
    public Button buttons;
    // Start is called before the first frame update
    void Start()
    {
        Buttons();
    }
    void Buttons()
    {
        buttons.onClick.AddListener(OneClick);
    }
    
    void OneClick()
    {
        FindObjectOfType<UiManager3>().SendMessage("ShowWhat", "主机");//如这里我想传给一个叫UiManager3脚本下的ShowWhat方法,传参类型是string类型
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UiManager3 : MonoBehaviour
{
    void ShowWhat(string name)
    {
        Debug.log(name);//界面会输出传过来的可以实现跨脚本传递参数
    }
}

该方法能够很方便地实现跨脚本传参,但有几个要点,

  1. 首先是要确定被传参的脚本是active也就是存在的(或者说是挂在某个物体下并且该物体以及该脚本都是打勾的)。如果不存在的话调用时是不会报错的,也就是很容易在后期找不到出错的地方在哪里。

  2. 其次就是这种传递参数的方法相较于delegate(委托)的效率会低,相关比较效率的文章详见。
    这里放上别人文章的链接:
    Unity中SendMessage和Delegate效率比较

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值