> 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/getclosestwaypoint.md).

# GetClosestWaypoint

### Description

Get the closest waypoint to a position. Uses a direction vector to select the correct lane.

### Declaration&#x20;

```csharp
public static int GetClosestWaypoint(Vector3 position, Vector3 direction)
```

### Parameters

<table><thead><tr><th width="209">Name</th><th>Description</th></tr></thead><tbody><tr><td><strong>position</strong></td><td>The index of the vehicle to be instantiated. Can be active or inactive at the time of instantiation.</td></tr><tr><td><strong>direction</strong></td><td>The vehicle will be instantiated with the front wheels axis on this position.</td></tr></tbody></table>

### Returns

**int** - The index of the closest waypoint.

### 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);
    }
}

```
