Class VehicleController
VehicleController collision handling. Forwards Unity's OnCollisionEnter to a UnityEvent the damage system and any gameplay code can subscribe to.
Implements
Inherited Members
Namespace: NWH.VehiclePhysics2
Assembly: NWH.VehiclePhysics2.dll
Syntax
[RequireComponent(typeof(Rigidbody))]
[DisallowMultipleComponent]
[DefaultExecutionOrder(90)]
public class VehicleController : Vehicle, ISubstepCallback
Remarks
Goes on the vehicle root GameObject alongside a Rigidbody; VehicleSetupWizard can do the setup. All physics is in SI units. Fixed Timestep should be 0.01667 (60Hz) or lower on desktop and 0.02 to 0.03 on mobile.
Fields
DEFAULT_RESOURCES_PATH
Default path in Resources folder where NWH Vehicle Physics 2 default assets are located. Used for loading default configurations during vehicle setup.
Declaration
public const string DEFAULT_RESOURCES_PATH = "NWH Vehicle Physics 2/Defaults/"
Field Value
| Type | Description |
|---|---|
| string |
_isInitialized
Internal flag tracking whether the vehicle has completed initialization. Set to true after all components are initialized and onVehicleInitialized event is invoked.
Declaration
protected bool _isInitialized
Field Value
| Type | Description |
|---|---|
| bool |
_multiplayerState
Cached multiplayer state used for network synchronization. Updated by GetMultiplayerState() and applied by SetMultiplayerState().
Declaration
[NonSerialized]
protected VehicleController.MultiplayerState _multiplayerState
Field Value
| Type | Description |
|---|---|
| VehicleController.MultiplayerState |
activeLOD
Active LOD instance, picked from the StateSettings list by camera distance.
Declaration
[NonSerialized]
[Tooltip("Currently active LOD.")]
public LOD activeLOD
Field Value
| Type | Description |
|---|---|
| LOD |
activeLODIndex
Index of the active LOD level. 0 is the closest and highest detail, higher indices are further out. -2 means initialization failed and -1 means no LOD is assigned.
Declaration
[NonSerialized]
[Tooltip("Currently active LOD index.")]
public int activeLODIndex
Field Value
| Type | Description |
|---|---|
| int |
brakes
Brake system component managing brake torque application and handbrake functionality.
Declaration
public Brakes brakes
Field Value
| Type | Description |
|---|---|
| Brakes |
deltaTime
Cached value of Time.deltaTime for performance optimization. Updated each frame in Update().
Declaration
[NonSerialized]
[Tooltip("Cached Time.deltaTime;")]
public float deltaTime
Field Value
| Type | Description |
|---|---|
| float |
dimensions
Vehicle dimensions in meters (Width x Height x Length). Used for physics calculations, LOD checks, and gizmo visualization.
Declaration
[Tooltip("Vehicle dimensions. Width x Height x Length")]
public Vector3 dimensions
Field Value
| Type | Description |
|---|---|
| Vector3 |
Remarks
Feeds the aerodynamic frontal and side areas, the inertia tensor and the CoM approximation.
dimensionsGizmoOffset
Local-space offset for the dimensions gizmo, for models whose origin is not centered. Gizmo only, no effect on physics.
Declaration
[Tooltip("Offset used to display dimensions gizmo in case the model origin is not properly positioned.")]
public Vector3 dimensionsGizmoOffset
Field Value
| Type | Description |
|---|---|
| Vector3 |
effectsManager
Effects system managing visual and auditory effects like skidmarks, particles, and lights.
Declaration
public EffectManager effectsManager
Field Value
| Type | Description |
|---|---|
| EffectManager |
fixedDeltaTime
Cached value of Time.fixedDeltaTime for performance optimization. Updated each FixedUpdate().
Declaration
[NonSerialized]
[Tooltip(" Cached Time.fixedDeltaTime.")]
public float fixedDeltaTime
Field Value
| Type | Description |
|---|---|
| float |
groundDetection
Ground detection system for identifying surface types and properties under wheels. Integrates with SurfaceMaps to determine friction, effects, and sounds per surface.
Declaration
public GroundDetection groundDetection
Field Value
| Type | Description |
|---|---|
| GroundDetection |
input
Input handling component that processes player input and converts it to vehicle states. Supports multiple input providers including InputManager, InputSystem, and mobile touch.
Declaration
public VehicleInputHandler input
Field Value
| Type | Description |
|---|---|
| VehicleInputHandler |
isAttachedAsTrailer
True when this VehicleController is currently attached as a trailer to a towing vehicle. Set by TrailerModule on attach/detach.
Declaration
[NonSerialized]
public bool isAttachedAsTrailer
Field Value
| Type | Description |
|---|---|
| bool |
Remarks
Brakes.cs reads this to suppress the trailer's off-throttle / reverse / idle auto-brake heuristics so it doesn't brake out of phase with the tractor. The input swap is handled separately: TrailerModule.OnAttach seeds input.swapInputInReverse from the tractor's resolved swap and TrailerHitchModule re-mirrors it each tick.
lateralSlipThreshold
Threshold for detecting lateral wheel slip (sideways sliding). When a wheel's lateral slip is below this value, skid effects and sounds are not triggered.
Declaration
[Tooltip("Used as a threshold value for lateral slip. When absolute lateral slip of a wheel is\r\nlower than this value wheel is considered to have no lateral slip (wheel skid). Used mostly for effects and sound.")]
public float lateralSlipThreshold
Field Value
| Type | Description |
|---|---|
| float |
Remarks
Effects and sound only, no effect on handling.
lodCamera
Camera the LOD distance is measured from. Falls back to Camera.main when null, and is re-resolved on each check so a swap takes effect immediately.
Declaration
[FormerlySerializedAs("LODCamera")]
[Tooltip("Camera from which the LOD distance will be measured.\r\nTo use Camera.main instead, leave empty/null.")]
public Camera lodCamera
Field Value
| Type | Description |
|---|---|
| Camera |
longitudinalSlipThreshold
Threshold for detecting longitudinal wheel slip (wheelspin/lockup). When a wheel's longitudinal slip is below this value, wheelspin effects and sounds are not triggered.
Declaration
[Tooltip("Used as a threshold value for longitudinal slip. When absolute longitudinal slip of a wheel is\r\nlower than this value wheel is considered to have no longitudinal slip (wheel spin). Used mostly for effects and sound.")]
public float longitudinalSlipThreshold
Field Value
| Type | Description |
|---|---|
| float |
Remarks
Effects and sound only, no effect on handling.
moduleManager
Module management system for optional vehicle features like ABS, TCS, cruise control, etc. Modules can be added or removed at runtime to extend vehicle functionality.
Declaration
public ModuleManager moduleManager
Field Value
| Type | Description |
|---|---|
| ModuleManager |
onCollision
Fired when the vehicle collides with another object. Carries the Unity Collision, so contact points, relative velocity and the other collider are all available.
Declaration
[Tooltip("Called when a collision happens.")]
public UnityEvent<Collision> onCollision
Field Value
| Type | Description |
|---|---|
| UnityEvent<Collision> |
onLODChanged
Fired whenever the vehicle crosses an LOD distance threshold and activeLODIndex changes.
Declaration
[NonSerialized]
[Tooltip("Called when active LOD is changed.")]
public UnityEvent onLODChanged
Field Value
| Type | Description |
|---|---|
| UnityEvent |
onVehicleInitialized
Invoked at the end of Start(), once every VehicleComponent is initialized and the state settings are loaded. Every vehicle system is safe to touch from here on.
Declaration
[NonSerialized]
[Tooltip("Called after the vehicle has finished initializing.")]
public UnityEvent onVehicleInitialized
Field Value
| Type | Description |
|---|---|
| UnityEvent |
onVehicleInitializing
Invoked after component ownership and states are loaded, before components are enabled.
Declaration
[NonSerialized]
[Tooltip("Called before vehicle components are enabled.")]
public UnityEvent onVehicleInitializing
Field Value
| Type | Description |
|---|---|
| UnityEvent |
powertrain
Powertrain system managing engine, transmission, clutch, differentials, and wheels. The core component responsible for converting throttle input into wheel torque.
Declaration
public Powertrain powertrain
Field Value
| Type | Description |
|---|---|
| Powertrain |
realtimeSinceStartup
Cached value of Time.realtimeSinceStartup for performance optimization. Updated each frame in Update().
Declaration
[NonSerialized]
[Tooltip("Cached version of the Time.realtimeSinceStartup")]
public float realtimeSinceStartup
Field Value
| Type | Description |
|---|---|
| float |
runAutomaticValidation
Enables automatic validation of vehicle setup in the Unity Editor. When true, validates the vehicle configuration whenever Inspector values change.
Declaration
[Tooltip("Should the VC_Validate() be run on each Unity Validate()?")]
public bool runAutomaticValidation
Field Value
| Type | Description |
|---|---|
| bool |
Remarks
Flags missing components, non-unit root scale, bad physics settings and similar. Editor only. Turn it off if the messages get noisy mid-setup.
soundManager
Sound system managing engine audio, transmission sounds, and other vehicle sound effects.
Declaration
public SoundManager soundManager
Field Value
| Type | Description |
|---|---|
| SoundManager |
stateSettings
ScriptableObject containing state and LOD configuration for all vehicle components. Controls which components are active at different LOD levels for performance optimization.
Declaration
[Tooltip("State settings for the current vehicle.\r\nState settings determine which components are enabled or disabled, as well as which LOD they belong to.")]
public StateSettings stateSettings
Field Value
| Type | Description |
|---|---|
| StateSettings |
Remarks
Shared between vehicles of the same type, so edits hit every vehicle referencing the asset. Create via Project > Create > NWH Vehicle Physics > State Settings.
steering
Steering system managing wheel angle calculations and steering responses. Includes support for Ackermann geometry and speed-sensitive steering.
Declaration
public Steering steering
Field Value
| Type | Description |
|---|---|
| Steering |
vehicleToCamDistance
Distance in meters between the vehicle and the LOD camera, refreshed every 0.2 seconds.
Declaration
[NonSerialized]
[Tooltip("Distance between camera and vehicle used for determining LOD.")]
public float vehicleToCamDistance
Field Value
| Type | Description |
|---|---|
| float |
wheelbase
Longitudinal distance between the front-most and rear-most wheels, in meters. Set by Steering on initialization from wheel local z; -1 until then, and -1 when fewer than two wheels have a WheelController.
Declaration
[Tooltip(" Longitudinal distance between the front-most and rear-most wheels, in meters.\r\n Set by Steering on initialization; -1 until then, and -1 when fewer than two wheels have a WheelController.")]
public float wheelbase
Field Value
| Type | Description |
|---|---|
| float |
Remarks
Valid at any axle count. Test with > SMALL_NUMBER rather than != 0, the unset value is -1. Used for Ackermann steering geometry and the motorcycle lean cap.
Properties
Components
Gets a list of all VehicleComponents attached to this vehicle. Includes core components like Input, Sound, Modules, Steering, Powertrain, Effects, Brakes, and GroundDetection.
Declaration
public List<VehicleComponent> Components { get; }
Property Value
| Type | Description |
|---|---|
| List<VehicleComponent> | List of all vehicle components |
Remarks
Built once and cached. Do not modify it directly; add and remove modules through ModuleManager.
IsInitialized
Indicates whether the vehicle and all its components have been fully initialized. Always check this before accessing vehicle components from external scripts.
Declaration
public bool IsInitialized { get; }
Property Value
| Type | Description |
|---|---|
| bool | True if initialization is complete, false otherwise |
Remarks
False through Awake() and early Start(), true once onVehicleInitialized has fired. Touching components before then can throw NullReferenceException.
WorldEnginePosition
Gets the engine position in world space. Used for 3D positional audio and particle effect placement.
Declaration
public Vector3 WorldEnginePosition { get; }
Property Value
| Type | Description |
|---|---|
| Vector3 | World space position of the engine |
WorldExhaustPosition
Gets the exhaust position in world space. Used for exhaust particle effects and sound source positioning.
Declaration
public Vector3 WorldExhaustPosition { get; }
Property Value
| Type | Description |
|---|---|
| Vector3 | World space position of the exhaust |
WorldTransmissionPosition
Gets the transmission position in world space. Used for transmission whine and gear shift sound positioning.
Declaration
public Vector3 WorldTransmissionPosition { get; }
Property Value
| Type | Description |
|---|---|
| Vector3 | World space position of the transmission |
Methods
Awake()
Declaration
public override void Awake()
Overrides
BreakStaticFriction(bool)
Forces all grounded wheels to exit static friction mode. Useful for synchronizing friction state with attached trailers.
Declaration
public void BreakStaticFriction(bool clearFilterHistory = true)
Parameters
| Type | Name | Description |
|---|---|---|
| bool | clearFilterHistory |
FixedUpdate()
Declaration
public override void FixedUpdate()
Overrides
GetMultiplayerState()
Captures the current vehicle state for network transmission. Call this on the authoritative client/server before sending data.
Declaration
public VehicleController.MultiplayerState GetMultiplayerState()
Returns
| Type | Description |
|---|---|
| VehicleController.MultiplayerState | Struct containing all synchronized vehicle state data |
Remarks
Consuming read: the momentary flags (shift, engine start/stop, trailer, cruise, flip over) report every pulse seen since the previous call and are cleared by it. Call it only from the network sampler, not from telemetry, or pulses will be sent to neither.
IsFullyGrounded()
Checks if all vehicle wheels are currently in contact with the ground. Useful for determining if the vehicle is stable for certain operations.
Declaration
public bool IsFullyGrounded()
Returns
| Type | Description |
|---|---|
| bool | True if all wheels are grounded, false if any wheel is airborne |
IsGrounded()
Checks if at least one wheel is in contact with the ground. Use this to detect if the vehicle is airborne.
Declaration
public bool IsGrounded()
Returns
| Type | Description |
|---|---|
| bool | True if any wheel is grounded, false if completely airborne |
OnAutomaticInputAvailabilityChanged(bool)
Called immediately when VehicleChanger grants or revokes permission to poll shared automatic input. Derived controllers use this to clear cached controls before the next physics step.
Declaration
protected override void OnAutomaticInputAvailabilityChanged(bool isAvailable)
Parameters
| Type | Name | Description |
|---|---|---|
| bool | isAvailable |
Overrides
OnBeforeSubstep(float, WheelControllerGroup)
Runs the powertrain integration before each wheel substep, using the substep dt.
Declaration
public void OnBeforeSubstep(float substepDt, WheelControllerGroup group)
Parameters
| Type | Name | Description |
|---|---|---|
| float | substepDt | Delta time for this substep. |
| WheelControllerGroup | group | Rigidbody group holding state and wheel list. |
OnDisable()
Declaration
public override void OnDisable()
Overrides
OnEnable()
Declaration
public override void OnEnable()
Overrides
Reset()
Declaration
public virtual void Reset()
SetDefaults()
Resets the vehicle and all its components to default values. Loads default assets from Resources folder and configures standard vehicle setup.
Declaration
public virtual void SetDefaults()
Remarks
Runs when the component is first added or on Inspector Reset. Defaults come from 'NWH Vehicle Physics 2/Defaults/' in Resources. Override for custom defaults.
SetMultiplayerMode(bool)
Switches the vehicle between locally driven and network-proxy input modes. Call this whenever transport ownership changes, before sending or applying state.
Declaration
public void SetMultiplayerMode(bool isRemote)
Parameters
| Type | Name | Description |
|---|---|---|
| bool | isRemote | True when this instance is controlled by a remote peer. |
SetMultiplayerState(MultiplayerState)
Applies received network state to the vehicle. Call this on non-authoritative clients after receiving data.
Declaration
public bool SetMultiplayerState(VehicleController.MultiplayerState inboundState)
Parameters
| Type | Name | Description |
|---|---|---|
| VehicleController.MultiplayerState | inboundState | State data received from the network |
Returns
| Type | Description |
|---|---|
| bool | True if state was successfully applied |
Remarks
Clears autoSetInput so local input cannot overwrite the received state.
Update()
Declaration
public virtual void Update()
UpdateComponentLODs()
Re-evaluates every component against the current LOD level. A component with LOD index -1 ignores the LOD system.
Declaration
protected virtual void UpdateComponentLODs()
VC_LogWarning(string)
Logs a validation warning with vehicle name prefix and prefab handling note.
Declaration
public void VC_LogWarning(string message)
Parameters
| Type | Name | Description |
|---|---|---|
| string | message |
Validate()
Validates vehicle setup: scale, components, physics settings, wheel config, etc. Outputs warnings to Console. Editor-only, runs automatically when runAutomaticValidation is true.
Declaration
public void Validate()