您最多选择25个主题 主题必须以中文或者字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 

1.9 KiB

ROS–Unity Integration: Subscriber

Create a simple Unity scene which subscribes to a ROS topic to change the colour of a GameObject.

Setting Up

Create Unity Subscriber

  • In Unity, create a new C# script and name it RosSubscriberExample. Paste the following code into the new script file. (Alternatively, you can drag the script file into Unity from tutorials/ros_unity_integration/unity_scripts/RosSubscriberExample.cs.)
using UnityEngine;
using Unity.Robotics.ROSTCPConnector;
using RosColor = RosMessageTypes.UnityRoboticsDemo.UnityColorMsg;

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);
    }
}
  • Create an empty GameObject and name it RosSubscriber

  • Attach the RosSubscriberExample script to the RosSubscriber GameObject and drag the cube GameObject onto the cube parameter in the Inspector window.

  • Press play in the editor

In ROS Terminal Window

Let's send a color message to change the color of the cube GameObject in Unity to a random color.

a) ros1 In ROS1, run: rosrun unity_robotics_demo color_publisher.py

b) ros2 In ROS2, instead run: ros2 run unity_robotics_demo color_publisher

Please reference networking troubleshooting doc if any errors are thrown.

Continue to the ROS–Unity Integration Unity Service.