2.7 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 ROS
(Skip to Setting Up Unity Scene if you already did the Publisher tutorial.)
-
Copy the
tutorials/ros_packages/robotics_demo
folder of this repo into thesrc
folder in your Catkin workspace. -
Follow the ROS–Unity Initial Setup guide.
-
Open a new terminal window, navigate to your Catkin workspace, and run the following commands:
source devel/setup.bash rosrun robotics_demo server_endpoint.py
Once the server_endpoint has started, it will print something similar to [INFO] [1603488341.950794]: Starting server on 192.168.50.149:10000
.
- In Unity, we need to generate the C# code for the
UnityColor
message. OpenRobotics
->Generate ROS Messages...
.- Set the ROS message path to
PATH/TO/Unity-Robotics-Hub/tutorials/ros_packages/robotics_demo/
, expand the robotics_demo subfolder and clickBuild 2 msgs
.
- Set the ROS message path to
- The generated files will be saved in the default directory
Assets/RosMessages/RoboticsDemo/msg
.
Setting Up Unity Scene
- Create a script and name it
RosSubscriberExample.cs
- Paste the following code into
RosSubscriberExample.cs
- Note Script can be found at
tutorials/ros_unity_integration/unity_scripts
- Note Script can be found at
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);
}
}
-
Create an empty GameObject and name it
RosSubscriber
-
Attach the
RosSubscriberExample
script to theRosSubscriber
GameObject and drag the cube GameObject onto thecube
parameter in the Inspector window. -
From the Unity menu bar, open
Robotics/ROS Settings
, and set theROS IP Address
variable to your ROS IP. -
Press play in the editor
In ROS Terminal Window
- After the scene has entered Play mode, run the following command:
rosrun robotics_demo color_publisher.py
to change the color of the cube GameObject in Unity to a random color
Please reference networking troubleshooting doc if any errors are thrown.
Continue to the ROS–Unity Integration Service.