In ROS2 is it possible to set GAZEBO_MODEL_PATH in launch file?

I use ROS2 Galactic and have a package that spawn a URDF robot model in Gazebo. The problem is that the URDF model uses meshes files and Gazebo is not able to find them if I don’t append the package install path to GAZEBO_MODEL_PATH.
Using the following line the model load without problem:

export GAZEBO_MODEL_PATH=$GAZEBO_MODEL_PATH:/home/ros/Documents/ROS2/ros2_ws/install/mars_robot/share/mars_robot

But I am wondering if it is possible to set that environment variable inside a launch file. I have tried with the following code but it doesn’t work.

    import os
    import xacro
    
    from ament_index_python.packages import get_package_share_directory
    from launch import LaunchDescription
    from launch.actions import IncludeLaunchDescription 
    from launch.launch_description_sources import PythonLaunchDescriptionSource
    from launch_ros.actions import Node
    from launch.actions import SetEnvironmentVariable
    
    def generate_launch_description():
    
        gazebo = IncludeLaunchDescription(
                    PythonLaunchDescriptionSource([os.path.join(
                        get_package_share_directory('gazebo_ros'), 'launch'), '/gazebo.launch.py']),
                 )
    
        xacro_robot_pkg_path = os.path.join(
            get_package_share_directory('mars_robot'))
    
        xacro_file = os.path.join(xacro_robot_pkg_path,
                                  'urdf',
                                  'mars_robot.xacro')
    
        doc = xacro.parse(open(xacro_file))
        xacro.process_doc(doc)
        params = {'robot_description': doc.toxml()}
    
        node_robot_state_publisher = Node(
            package='robot_state_publisher',
            executable='robot_state_publisher',
            output='screen',
            parameters=[params]
        )
    
        spawn_entity = Node(package='gazebo_ros', executable='spawn_entity.py',
                            arguments=['-topic', 'robot_description',
                                       '-entity', 'mars_robot'],
                            output='screen')
    
        return launch.LaunchDescription([
            SetEnvironmentVariable(name='GAZEBO_MODEL_PATH', value='/home/ros/Documents/ROS2/ros2_ws/install/mars_robot/share/mars_robot'),
            gazebo,
            node_robot_state_publisher,
            spawn_entity,
        ])

I have also try this line in the code instead of using SetEnvironmentVariable, but also doesn’t work.

os.environ['GAZEBO_MODEL_PATH'] = os.path.join(get_package_share_directory('your_gazebo_pkg'),'models')

Why the behavior is different if I use export to set the environment variable or do it inside the launch file? What am I doing wrong?

Thanks for your help and best regards.

This topic was automatically closed after 6 days. New replies are no longer allowed.