Unity3D _脚本之间通信

通过查阅资料,看到unity3d的通信有以下几种方式:
1.利用在脚本A中定义对外接口函数,然后在脚本B中找到A所在的对象,再找到脚本A,进而调用里面的对外接口函数,这个方法在我的《unity3D NGUI中button响应事件实现》这篇文章中有仔细说明,可以参考。
2.还有一个是利用SendMessage的方法来实现脚本互相通信。
首先在A脚本中编写对外接口函数,如下所示:

using UnityEngine;  
using System.Collections;  

  public class A : MonoBehaviour {  
  public void Show_nunber(int n)  

      {  

      print("num: " + n );  

      }  
}  

然后在脚本B中利用SendMessage机制调用脚本A里面的Show_number函数。如下:

using UnityEngine;  
using System.Collections;  

 public class B : MonoBehaviour {  

 public GameObject Obj;//A脚本绑定在一个物体上的时候,再把脚本B拖拽到这个GameObject  
  void Start ()   
    {  

   Obj.SendMessage("Show_number","10");//相当于调用脚本B里面的函数,第一个参数是函数名,第二个传递的整型参数  

  }  

这样就可以实现两个不同对象上的脚本相互通信了。

以上引用于博客:

http://blog.csdn.net/u012805027/article/details/17102393

但是我后来发现,我在最开始想要实现的通信,并不是这种“复杂”的传递参数。有一种更简单的方法,直接调用public类的函数就可以了。
比如,有一个串口通信类
public class SerialPortReciever : MonoBehaviour{}
在另一个类中直接实例化一个对象

public class Anima_Control : MonoBehaviour {
    public SerialPortReciever Obj;//  
    ……
if (Obj.R1 == 2)
        {
            animation["first"].speed = 1f;
            animation.Play("first");
            ……
        }
    }

其实通信没有那么复杂。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Unity 服务器通信协议可以使用多种方式,例如: 1. TCP/IP协议:通过使用Socket或TcpClient等Unity自带的类库实现。 2. UDP协议:通过使用UdpClient等Unity自带的类库实现。 3. HTTP协议:通过使用HttpWebRequest或HttpClient等Unity自带的类库实现。 而在Unity中实现HTTP通信,可以使用以下步骤: 1. 在Unity中创建一个空对象,并为其添加一个C#脚本。 2. 在脚本中使用HttpWebRequest或HttpClient等Unity自带的类库,发送HTTP请求。 3. 处理服务器返回的响应,例如解析JSON或XML数据。 以下是一个简单的HTTP GET请求的示例代码: ```csharp using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Net; using System.IO; public class HttpExample : MonoBehaviour { // URL to request private const string url = "https://api.github.com/"; // Start is called before the first frame update void Start() { // Create a new HttpWebRequest HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; // Send the request and get the response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Read the response stream Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseText = reader.ReadToEnd(); // Log the response to the console Debug.Log(responseText); // Clean up resources reader.Close(); dataStream.Close(); response.Close(); } } ``` 该示例使用HttpWebRequest类发送了一个HTTP GET请求,并打印了响应文本。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值