NWH Common
Search Results for

    VehicleChanger

    VehicleChanger manages vehicle switching in a scene. It supports instant switching (press a button to cycle) and character-based enter/exit (GTA-style walking to vehicles).


    Overview

    The vehicle enter/exit system uses:

    • VehicleChanger - Scene-level singleton managing vehicle switching
    • Vehicle - Base class tracking active vehicles globally
    • EnterExitPoints - Tag-based GameObjects marking entry locations

    No dedicated Seat or Portal classes are needed. Entry points are simple tagged GameObjects.


    Operation Modes

    Instant Mode

    Switch directly between vehicles without a character:

    Partial configuration example:

    characterBased = false;
    
    • Press button to cycle through vehicles immediately
    • No character object needed
    • Useful for vehicle showcases, testing, arcade games

    Character-Based Mode

    GTA-style walking to vehicles and entering:

    Partial configuration example:

    characterBased = true;
    
    • Player walks to vehicle entry points
    • Enter/exit at designated EnterExitPoints
    • Character object enables/disables on entry/exit

    Quick Setup

    Instant Mode Setup

    1. Add VehicleChanger component to a scene GameObject
    2. Populate the vehicles list with your vehicles
    3. Set characterBased = false
    4. Configure input for NextVehicle/PreviousVehicle

    Character-Based Setup

    1. Add VehicleChanger component to a scene GameObject
    2. Populate the vehicles list with your vehicles
    3. Set characterBased = true
    4. Assign your player object to characterObject
    5. For each vehicle:
      • Create an empty GameObject child at each door position
      • Tag it with "EnterExitPoint" (or your custom tag)

    Properties

    Core Settings

    Property Type Default Description
    vehicles List<Vehicle> - All managed vehicles in the scene
    activeVehicleIndex int 0 Currently active vehicle index
    characterBased bool false Enable character enter/exit mode
    characterObject GameObject null Player character object

    Entry Settings

    Property Type Default Description
    enterDistance float 2.0 Maximum horizontal distance to enter (meters). The inspector slider covers 0.2 to 3
    enterExitTag string "EnterExitPoint" Tag for entry point GameObjects
    maxEnterExitVehicleSpeed float 2.0 Max vehicle Rigidbody speed for entry/exit (m/s)

    The tag in enterExitTag must exist under Project Settings > Tags and Layers. If it does not, the component logs one warning and finds no entry points; entering a vehicle is then impossible in character mode.

    Behavior Settings

    Property Type Default Description
    putOtherVehiclesToSleep bool true Disable inactive vehicles
    startInVehicle bool false Begin scene inside active vehicle

    EnterExitPoint Setup

    Entry points are simple tagged GameObjects, not dedicated components.

    Creating Entry Points

    1. Create an empty GameObject at each door/entry position
    2. Parent it to the vehicle's transform hierarchy
    3. Tag it with enterExitTag (default: "EnterExitPoint")
    Vehicle (VehicleController)
    ├── Body
    ├── Wheels
    └── EnterExitPoints
        ├── DriverDoor (tag: EnterExitPoint)
        ├── PassengerDoor (tag: EnterExitPoint)
        └── RearDoor (tag: EnterExitPoint)
    

    Distance Calculation

    • The nearest entry point is chosen by full 3D distance from the character.
    • Whether that nearest point is close enough is then tested on the horizontal plane only, against enterDistance. A point directly above or below the character counts as reachable.
    • The vehicle that owns the nearest point, found with GetComponentInParent<Vehicle>(), is the one that can be entered. Parent the entry points under the vehicle.

    Character Location States

    The system tracks character position relative to vehicles:

    Source excerpt (the enum is nested in VehicleChanger):

    public enum CharacterLocation
    {
        OutOfRange,  // Too far from any vehicle
        Near,        // Close enough to enter (< enterDistance)
        Inside       // Currently in vehicle
    }
    

    Access current state:

    Partial access example:

    VehicleChanger.CharacterLocation location = VehicleChanger.Instance.location;
    

    API Reference

    Singleton Access

    Partial access example:

    VehicleChanger changer = VehicleChanger.Instance;
    

    Vehicle Switching

    Partial usage example (changer is a VehicleChanger reference):

    // Switch to specific vehicle by index
    changer.ChangeVehicle(2);
    
    // Switch to specific vehicle by reference
    changer.ChangeVehicle(myVehicle);
    
    // Cycle through vehicles
    changer.NextVehicle();
    changer.PreviousVehicle();
    

    Enter/Exit

    Partial usage example (vehicle and currentVehicle are Vehicle references):

    // Enter a vehicle (character mode)
    changer.EnterVehicle(vehicle);
    
    // Exit current vehicle (character mode)
    changer.ExitVehicle(currentVehicle);
    

    Vehicle Registration

    Partial usage example (spawnedVehicle and destroyedVehicle are Vehicle references):

    // Register a spawned vehicle
    changer.RegisterVehicle(spawnedVehicle);
    
    // Deregister a destroyed vehicle
    changer.DeregisterVehicle(destroyedVehicle);
    

    Enter/Exit Points

    RefreshEnterExitPoints() requests a rescan of tagged points on the next update. Registering or deregistering a vehicle already does this, as does loading a scene; call it only when entry points are added or removed on their own.

    Activation Control

    Partial usage example (changer is a VehicleChanger reference):

    // Deactivate all except active vehicle
    changer.DeactivateAllExceptActive();
    
    // Deactivate all including active (exit in character mode)
    changer.DeactivateAllIncludingActive();
    

    Events

    VehicleChanger Events

    onVehicleChanged and onDeactivateAll are drawn in an Events subsection in the inspector, so persistent listeners can be wired there instead of in code.

    Partial listener-registration example:

    // Vehicle changed (includes enter/exit)
    VehicleChanger.Instance.onVehicleChanged.AddListener(() => {
        Debug.Log("Vehicle changed!");
    });
    
    // All vehicles deactivated (exit in character mode)
    VehicleChanger.Instance.onDeactivateAll.AddListener(() => {
        Debug.Log("Exited all vehicles");
    });
    

    Global Vehicle Tracking

    Partial listener-registration example:

    // Track active vehicle changes globally
    Vehicle.onActiveVehicleChanged.AddListener((previous, current) => {
        Debug.Log($"Changed from {previous?.name} to {current?.name}");
    });
    
    // Access static vehicle lists
    List<Vehicle> allActive = Vehicle.ActiveVehicles;
    Vehicle currentActive = Vehicle.ActiveVehicle;
    

    Enter/Exit Flow

    Character-Based Entry

    1. Character approaches EnterExitPoint
    2. Distance < enterDistance
       └── location = Near
    3. Check: Rigidbody speed < maxEnterExitVehicleSpeed
    4. Input triggers ChangeVehicle
    5. Store relative enter position
    6. characterObject.SetActive(false)
    7. location = Inside
    8. Vehicle.enabled = true
       └── Adds to Vehicle.ActiveVehicles
    

    Character-Based Exit

    1. location == Inside
    2. Check: Rigidbody speed < maxEnterExitVehicleSpeed
    3. Input triggers exit
    4. DeactivateAllIncludingActive()
    5. Character positioned at stored relative location
    6. characterObject.transform.forward = vehicle.transform.right (face outward)
    7. characterObject.SetActive(true)
    8. location = OutOfRange
    

    Instant Mode Switching

    1. Input triggers NextVehicle()
    2. activeVehicleIndex++
    3. DeactivateAllExceptActive()
    4. onVehicleChanged fires
    

    Character Positioning

    On Enter

    The relative position is stored for later use:

    Implementation excerpt (from inside VehicleChanger.EnterVehicle()):

    characterObject.SetActive(false);
    _relativeEnterPosition =
        v.transform.InverseTransformPoint(characterObject.transform.position);
    location = VehicleChanger.CharacterLocation.Inside;
    

    On Exit

    Character is placed back at the relative position, facing outward:

    Implementation excerpt (from inside VehicleChanger.ExitVehicle()):

    characterObject.transform.position =
        v.transform.TransformPoint(_relativeEnterPosition);
    characterObject.transform.forward = v.transform.right;
    characterObject.transform.up = Vector3.up;
    characterObject.SetActive(true);
    

    Integration with Input

    Scene Input Provider

    Implementation excerpt:

    // Input is read from SceneInputProviderBase
    bool changeVehiclePressed =
        InputProvider.CombinedInput<SceneInputProviderBase>(i => i.ChangeVehicle());
    

    Default Keys

    Action Input Manager Input System
    Next Vehicle V ChangeVehicle action
    Enter/Exit V (near vehicle) ChangeVehicle action

    Custom Input

    Partial input example (place inside an update method):

    // Trigger vehicle change programmatically
    if (Input.GetKeyDown(KeyCode.E))
    {
        VehicleChanger.Instance.NextVehicle();
    }
    

    Performance Optimization

    putOtherVehiclesToSleep

    When enabled (default), inactive vehicles are disabled:

    Partial configuration example:

    putOtherVehiclesToSleep = true;
    

    Disabling inactive vehicles reduces physics calculations and Update/FixedUpdate overhead, leaving more CPU time for the active vehicle.

    Vehicles are re-enabled when switched to.

    Scene Loading

    Entry points are found with GameObject.FindGameObjectsWithTag(enterExitTag) and cached. The scan is repeated only when the cache is marked dirty: on scene load, on vehicle registration and deregistration, when a cached point has been destroyed, and on an explicit RefreshEnterExitPoints() call. Without that, the tag query would run on every update while the character is on foot.


    Usage Examples

    Basic Scene Setup

    Conceptual scene hierarchy:

    // Scene structure:
    // - VehicleChanger (singleton)
    // - Player (character, if using character mode)
    // - Vehicle1 (VehicleController)
    //   - EnterExitPoint (tagged)
    // - Vehicle2 (VehicleController)
    //   - EnterExitPoint (tagged)
    

    Runtime Vehicle Spawning

    Partial MonoBehaviour example (namespace imports and the containing class are omitted):

    public void SpawnVehicle(GameObject prefab, Vector3 position)
    {
        GameObject instance = Instantiate(prefab, position, Quaternion.identity);
        Vehicle vehicle = instance.GetComponent<Vehicle>();
    
        // Register with VehicleChanger
        VehicleChanger.Instance.RegisterVehicle(vehicle);
    
        // Optionally switch to it
        VehicleChanger.Instance.ChangeVehicle(vehicle);
    }
    
    public void DestroyVehicle(Vehicle vehicle)
    {
        // Deregister first
        VehicleChanger.Instance.DeregisterVehicle(vehicle);
    
        Destroy(vehicle.gameObject);
    }
    

    Custom Enter Logic

    Partial example (FindNearestVehicle() is an application-specific helper):

    public class CustomVehicleEntry : MonoBehaviour
    {
        public void TryEnterNearestVehicle()
        {
            VehicleChanger changer = VehicleChanger.Instance;
    
            if (!changer.characterBased) return;
            if (changer.location != VehicleChanger.CharacterLocation.Near) return;
    
            // Find nearest vehicle
            Vehicle nearest = FindNearestVehicle();
            if (nearest != null && nearest.VelocityMagnitude < changer.maxEnterExitVehicleSpeed)
            {
                changer.EnterVehicle(nearest);
            }
        }
    }
    

    Listening for Vehicle Changes

    Partial MonoBehaviour example (UpdateHUD() and the UI helpers are application methods):

    public class GameManager : MonoBehaviour
    {
        void Start()
        {
            // Listen to VehicleChanger events
            VehicleChanger.Instance.onVehicleChanged.AddListener(OnVehicleChanged);
    
            // Or listen to global Vehicle events
            Vehicle.onActiveVehicleChanged.AddListener(OnActiveVehicleChanged);
        }
    
        void OnVehicleChanged()
        {
            // Update UI, camera, etc.
            UpdateHUD();
        }
    
        void OnActiveVehicleChanged(Vehicle previous, Vehicle current)
        {
            // Handle vehicle change with references
            if (previous != null)
                DisableVehicleUI(previous);
            if (current != null)
                EnableVehicleUI(current);
        }
    }
    

    Limitations

    • Single occupant only - No passenger seat system
    • No seat assignment - All entry points are equivalent
    • Character teleports - No animation support built-in
    • Single instance - Singleton pattern, one per scene

    For more complex requirements (passengers, animations, seat selection), you may need to extend or replace this system.


    Vehicle Base Class

    The Vehicle class (base for VehicleController) provides static tracking:

    Static Properties

    Public API signatures (implementation bodies and initializers are abbreviated):

    // All currently enabled vehicles
    public static List<Vehicle> ActiveVehicles;
    
    // The most recently enabled player-controllable vehicle (read-only)
    public static Vehicle ActiveVehicle { get; }
    
    // Event when active vehicle changes
    public static UnityEvent<Vehicle, Vehicle> onActiveVehicleChanged;
    

    Instance Properties

    Property Description
    isPlayerControllable Can be ActiveVehicle (false for trailers)
    Speed Forward speed, always positive
    SpeedSigned Forward speed, negative in reverse
    VelocityMagnitude Actual speed regardless of direction

    Speed and SpeedSigned are the body-frame forward projection, so both collapse toward zero when the vehicle is sliding sideways. Use VelocityMagnitude for any is-it-moving threshold.


    Related Documentation

    • Input - Input system configuration
    • Cameras - Camera system
    • VehicleController (NWH Vehicle Physics 2) - Main vehicle component
    In this article
    Back to top Copyright © NWH - Vehicle Physics, Aerodynamics, Dynamic Water Physics