unity3d 2个脚本之间传值传递信息

分类栏目:unity3d教程

187

//unity菜鸡,将自己学习中的知识写下来。如若发现错误,希望可以私信。共同进步

在unity中,脚本之间传递信息有几种方式

第一种也是比较正统的吧,SendMessage函数,他有如下这几种形式:

1.SendMessage


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

methodName指的是需要接收本指令的函数,value即为所需传递到接收函数中的参数,options为如果未在目标函数中找到本方法的话是否需要引发Error操作

2.SendMessageUpwards


 原型:public void SendMessageUpwards(string methodName, object value = null, SendMessageOptions options = SendMessageOptions.RequireReceiver);

他的作用和SendMessage是差不多的,不过他会向目标函数及所有父函数传递信息;

3.BroadcastMessage

原型:public void BroadcastMessage(string methodName, object parameter = null, SendMessageOptions options = SendMessageOptions.RequireReceiver);
作用与Upwards有点相反,他可以向所有子对象传递信息

第二种则是我平时用的比较多的,因为也是刚开始学,所以不一定正确,但目前还是有用的,可以予以借鉴:

 我们可以直接在当前函数中声明一个需要被调用的函数的对象:例如我们现有一个名叫Inventory的脚本中有这样一个函数存在:

public void Calculate(int in)
{
    if(in == 0){
       debug.log("输入为0");
    }
}
在其余函数中,我们可以这样来调用此函数,并传递信息:

public Inventory Inv;
 
/*
    在使用public后在unity操作页面绑定被操作脚本,或者使用Private 在awake或者 start中挂载被操作脚本
*/
 
public void Test()
{
    Inv.Calculate(0);  //传递参数,并调用
}