> For the complete documentation index, see [llms.txt](https://gley.gitbook.io/mobile-traffic-system/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gley.gitbook.io/mobile-traffic-system/complete-api/instantiatetrafficvehicle.md).

# InstantiateTrafficVehicle

### Description

Instantiates a vehicle on the specified position with an initial velocity.&#x20;

This method is useful if you want to replace an existing vehicle that was driven outside of the traffic system, with a new one that behaves like a normal traffic vehicle.&#x20;

### Declaration&#x20;

```csharp
public static void InstantiateTrafficVehicle(int vehicleIndex, Vector3 frontWheelsPosition, Quaternion vehicleRotation, Vector3 initialVelocity, Vector3 initialAngularVelocity, int nextWaypointIndex)
```

### Parameters

<table><thead><tr><th width="209">Name</th><th>Description</th></tr></thead><tbody><tr><td>vehicleIndex</td><td>The index of the vehicle to be instantiated. Can be active or inactive at the time of instantiation.</td></tr><tr><td>frontWheelsPosition</td><td>The vehicle will be instantiated with the front wheels axis on this position.</td></tr><tr><td>vehicleRotation</td><td>The rotation of the instantiated vehicle.</td></tr><tr><td>initialVelocity</td><td>The initial linear velocity.</td></tr><tr><td>initialAngularVelocity</td><td>The initial angular velocity.</td></tr><tr><td>nextWaypointIndex</td><td>The waypoint the vehicle will go towards.</td></tr></tbody></table>

### Example

```csharp
using Gley.TrafficSystem;
using UnityEngine;

public class Test : MonoBehaviour
{
    public GameObject playerCarGo;

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            ShitchPlayerCarWithTrafficVehicle();
        }
    }

    private void SwitchPlayerCarWithTrafficVehicle()
    {
        // Get the current position and rotation of the player car
        Vector3 currentCarPosition = playerCarGo.transform.position;
        Quaternion currentCarRotation = playerCarGo.transform.rotation;

        // Get the rigidbody of the player car.
        Rigidbody manualRg = playerCarGo.GetComponent<Rigidbody>();

        // Deactivate the player car
        playerCarGo.SetActive(false);

        // Get the closest waypoint from the player car in the moving direction.
        // Direction is important because the closest waypoint might be on the other way.
        int nextWaypointIndex = API.GetClosestWaypoint(playerCarGo.transform.position, playerCarGo.transform.forward);

        // An index of the vehicle that looks exactly with the player car
        int trafficVehicleIndex = 0;

        // Instantiate the traffic vehicle
        API.InstantiateTrafficVehicle(trafficVehicleIndex, currentCarPosition, currentCarRotation, manualRg.velocity, manualRg.angularVelocity, nextWaypointIndex);
    }
}

```
