Implementation:CARLA simulator Carla Command SpawnActor Then
| Knowledge Sources | |
|---|---|
| Domains | Autonomous Driving Simulation, Client-Server Architecture |
| Last Updated | 2026-02-15 00:00 GMT |
Overview
Concrete tool for spawning actors in bulk with chained configuration commands using CARLA's batch command system, provided by the CARLA simulator.
Description
The carla.command.SpawnActor class creates a command object that, when executed by the server, spawns an actor from a given blueprint at a specified transform. The .then() method chains a follow-up command (such as SetAutopilot) that automatically receives the spawned actor's ID via the FutureActor placeholder.
The Client.apply_batch_sync() method sends a list of these command objects to the server in a single network call, executes them all within one tick, and returns a list of BatchResponse objects indicating success or failure for each command.
This combination is the standard pattern for spawning large numbers of NPC vehicles with autopilot enabled in CARLA traffic generation scripts. It replaces the much slower approach of calling world.spawn_actor() and vehicle.set_autopilot() individually for each vehicle.
Usage
Use SpawnActor(...).then(...) with apply_batch_sync() when spawning multiple NPC vehicles or pedestrians that need immediate post-spawn configuration (autopilot, AI controller attachment, etc.).
Code Reference
Source Location
- Repository: CARLA
- File:
PythonAPI/carla/src/Commands.cpp - Lines: L70-200
- Client Batch:
PythonAPI/carla/src/Client.cpp, L51-170
Signature
# Spawn command with chaining
carla.command.SpawnActor(blueprint: ActorBlueprint, transform: Transform) -> SpawnActor
SpawnActor.then(command: Command) -> SpawnActor
# Batch execution
Client.apply_batch_sync(commands: list[Command], do_tick: bool = False) -> list[command.Response]
# Common chained commands
carla.command.SetAutopilot(actor: Union[Actor, FutureActor], enabled: bool, tm_port: int = 8000)
carla.command.FutureActor # Placeholder for the actor ID from the parent SpawnActor command
Import
import carla
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| blueprint | carla.ActorBlueprint | Yes | The blueprint defining the actor type and configured attributes (vehicle model, color, etc.). |
| transform | carla.Transform | Yes | The world-space position and rotation at which to spawn the actor. |
| command (then) | carla.command.* | Yes | A follow-up command to execute after the actor is spawned. Typically SetAutopilot for vehicles.
|
| commands (apply_batch_sync) | list | Yes | A list of command objects (SpawnActor, DestroyActor, etc.) to execute in batch. |
| do_tick | bool | No (default: False) | If True, the server advances one simulation tick after executing all commands. Useful in synchronous mode. |
Outputs
| Name | Type | Description |
|---|---|---|
| return (apply_batch_sync) | list[command.Response] | A list of response objects, one per command. Each response has .error (str, empty on success) and .actor_id (int, the spawned actor's ID on success).
|
Usage Examples
Basic Example
import carla
import random
client = carla.Client('localhost', 2000)
client.set_timeout(10.0)
world = client.get_world()
# Get Traffic Manager port
traffic_manager = client.get_trafficmanager(8000)
tm_port = traffic_manager.get_port()
# Get vehicle blueprints and spawn points
blueprints = world.get_blueprint_library().filter('vehicle.*')
spawn_points = world.get_map().get_spawn_points()
random.shuffle(spawn_points)
# Build batch commands: spawn each vehicle and immediately enable autopilot
batch = []
for i, spawn_point in enumerate(spawn_points[:50]): # Spawn 50 vehicles
blueprint = random.choice(blueprints)
if blueprint.has_attribute('color'):
color = random.choice(blueprint.get_attribute('color').recommended_values)
blueprint.set_attribute('color', color)
batch.append(
carla.command.SpawnActor(blueprint, spawn_point)
.then(carla.command.SetAutopilot(carla.command.FutureActor, True, tm_port))
)
# Execute all spawn commands in a single server round-trip
results = client.apply_batch_sync(batch, do_tick=True)
# Collect successfully spawned vehicle IDs
vehicles_list = []
for response in results:
if response.error:
print(f"Spawn failed: {response.error}")
else:
vehicles_list.append(response.actor_id)
print(f"Successfully spawned {len(vehicles_list)} vehicles")
Spawning with Error Handling
import carla
import random
client = carla.Client('localhost', 2000)
client.set_timeout(10.0)
world = client.get_world()
traffic_manager = client.get_trafficmanager(8000)
traffic_manager.set_synchronous_mode(True)
tm_port = traffic_manager.get_port()
blueprints = world.get_blueprint_library().filter('vehicle.*')
# Filter to only 4-wheeled vehicles
blueprints = [bp for bp in blueprints
if int(bp.get_attribute('number_of_wheels')) == 4]
spawn_points = world.get_map().get_spawn_points()
number_of_vehicles = min(len(spawn_points), 100)
# Shuffle spawn points for random placement
random.shuffle(spawn_points)
batch = []
for i in range(number_of_vehicles):
bp = random.choice(blueprints)
if bp.has_attribute('color'):
bp.set_attribute('color', random.choice(
bp.get_attribute('color').recommended_values))
bp.set_attribute('role_name', 'autopilot')
batch.append(
carla.command.SpawnActor(bp, spawn_points[i])
.then(carla.command.SetAutopilot(carla.command.FutureActor, True, tm_port))
)
responses = client.apply_batch_sync(batch, do_tick=True)
# Track spawned vehicles for later cleanup
spawned_ids = []
failed_count = 0
for i, response in enumerate(responses):
if response.error:
failed_count += 1
else:
spawned_ids.append(response.actor_id)
print(f"Spawned: {len(spawned_ids)}, Failed: {failed_count}")