浏览代码

Update subscriber.md

/vidur-Updating-ROS-Unity-Tutorials
vidurvij-Unity 3 年前
当前提交
4e0f7ef1
共有 1 个文件被更改,包括 72 次插入0 次删除
  1. 72
      tutorials/ros_unity_integration/subscriber.md

72
tutorials/ros_unity_integration/subscriber.md


![](images/tcp_2.gif)
## ROSSubscriberExample script
```csharp
using UnityEngine;
using Unity.Robotics.ROSTCPConnector;
using RosColor = RosMessageTypes.RoboticsDemo.MUnityColor;
public class RosSubscriberExample : MonoBehaviour
{
public GameObject cube;
void Start()
{
ROSConnection.instance.Subscribe<RosColor>("color", ColorChange);
}
void ColorChange(RosColor colorMessage)
{
cube.GetComponent<Renderer>().material.color = new Color32((byte)colorMessage.r, (byte)colorMessage.g, (byte)colorMessage.b, (byte)colorMessage.a);
}
}
```
### Import Statements for Subscriber and Messages
```csharp
using UnityEngine;
using Unity.Robotics.ROSTCPConnector;
using RosColor = RosMessageTypes.RoboticsDemo.MUnityColor;
```
### Instantiating the ROS Subscriber in unity
```csharp
void Start()
{
ROSConnection.instance.Subscribe<RosColor>("color", ColorChange);
}
```
We declare the topic to be subscribed before the program execution starts. This is done in the `Start()` function of the MonoBehavior. We add the topic we want to subscribe to the internal dictionary of our ROSConnection instance using `Subscribe` API.
### Subscribe API
```csharp
public void Subscribe<T>(string topic, Action<T> callback)
```
### Summary
Its a non-static member of ROSConnection class. It is used to add a ROS subscriber to the internal ROSConnection Dictionary.
### Type Parameter
T: ROS message type published in the topic to be subscribed.
### Parameters
Parameters | Description |
| ------------- | ------------- |
| `string topic` | Name of the topic to be subscribed on the ROS machine |
| `Action<T> callback` | Callback function used to process the received message |
### Implementing the callback function
```csharp
void ColorChange(RosColor colorMessage)
{
cube.GetComponent<Renderer>().material.color = new Color32((byte)colorMessage.r, (byte)colorMessage.g, (byte)colorMessage.b, (byte)colorMessage.a);
}
```
After a message is received in Unity, a callback function is called to process the incoming message. The callback is a delegate which defines a function that receives one parameter and returns nothing as described [here](https://docs.microsoft.com/en-us/dotnet/api/system.action-1?view=net-5.0). In this Subscribe API, that parameter is the message published in the topic.
In this example we extract the color's attributes from the message and assign it to the cube's material.
> Please reference [networking troubleshooting](network.md) doc if any errors are thrown.
![](images/tcp_2.gif)
Continue to the [ROS–Unity Integration Service](service.md).
正在加载...
取消
保存