Class VehicleController
Partial class containing collision detection and handling for VehicleController. Provides Unity collision event handling and damage system integration.
Implements
Inherited Members
Namespace: NWH.VehiclePhysics2
Assembly: NWH.VehiclePhysics2.dll
Syntax
[RequireComponent(typeof(Rigidbody))]
[DisallowMultipleComponent]
[DefaultExecutionOrder(90)]
public class VehicleController : Vehicle, ISubstepCallback
Remarks
This partial class handles OnCollisionEnter events and provides a UnityEvent for custom collision response implementation. Can be used for damage systems, sound effects, visual effects, or gameplay mechanics triggered by collisions.
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
The currently active LOD instance containing distance and name information. Updated automatically based on camera distance.
Declaration
[NonSerialized]
[Tooltip("Currently active LOD.")]
public LOD activeLOD
Field Value
| Type | Description |
|---|---|
| LOD |
activeLODIndex
Index of the currently active LOD level. Lower values represent higher detail (closer to camera).
Declaration
[NonSerialized]
[Tooltip("Currently active LOD index.")]
public int activeLODIndex
Field Value
| Type | Description |
|---|---|
| int |
Remarks
Value of -2 indicates initialization failure. Value of 0 is highest detail (closest LOD). Higher values progressively reduce detail.
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
Typical values: Compact car (1.8, 1.4, 4.2), SUV (2.0, 1.8, 4.8), Truck (2.5, 3.0, 7.0). These dimensions affect inertia tensor calculations and center of mass approximation.
dimensionsGizmoOffset
Offset in local space for the dimensions gizmo visualization. Useful when the vehicle model origin is not centered.
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 |
Remarks
Only affects the yellow wire cube gizmo shown in Scene view when the vehicle is selected. Does not affect physics calculations.
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. Input-swap neutrality is handled separately by TrailerModule.OnAttach clearing input.swapInputInReverse.
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
Lower values (0.05-0.1) make effects more sensitive, triggering during slight slides. Higher values (0.2-0.3) only trigger effects during significant lateral sliding. Does not affect vehicle handling, only effects and sounds.
lodCamera
Camera used for LOD distance calculations. If null, Camera.main will be used automatically.
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 |
Remarks
Assign a specific camera for split-screen or multi-camera setups. The LOD system measures the distance from this camera to the vehicle transform. Changes to this field take effect immediately.
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
Lower values (0.1-0.2) make effects more sensitive, showing wheelspin during light acceleration. Higher values (0.4-0.5) only trigger effects during heavy wheelspin or hard braking. Does not affect vehicle handling, only effects and sounds.
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
Unity event triggered when the vehicle collides with another object. Provides collision data including contact points, impact force, and colliding object.
Declaration
[Tooltip("Called when a collision happens.")]
public UnityEvent<Collision> onCollision
Field Value
| Type | Description |
|---|---|
| UnityEvent<Collision> |
Remarks
Subscribe to this event to implement custom collision responses such as:
- Damage calculation based on impact force
- Collision sound effects and particle effects
- Score or gameplay changes
- Physics responses or vehicle deformation The Collision parameter contains all Unity collision data including relative velocity, contact points, and the other collider.
onLODChanged
Unity event invoked when the LOD level changes. Use this to trigger custom behaviors when detail level changes.
Declaration
[NonSerialized]
[Tooltip("Called when active LOD is changed.")]
public UnityEvent onLODChanged
Field Value
| Type | Description |
|---|---|
| UnityEvent |
Remarks
Called whenever the vehicle crosses an LOD distance threshold. Can be used to adjust visual quality, physics accuracy, or other custom systems.
onVehicleInitialized
Unity event invoked after all vehicle components have been initialized. Use this to run code that depends on the vehicle being fully set up.
Declaration
[NonSerialized]
[Tooltip("Called after the vehicle has finished initializing.")]
public UnityEvent onVehicleInitialized
Field Value
| Type | Description |
|---|---|
| UnityEvent |
Remarks
This event is called at the end of Start() after all VehicleComponents have been initialized and state settings have been loaded. Safe to access all vehicle systems after this event.
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
Validation checks for common setup issues like missing components, incorrect scale, invalid physics settings, etc. Disable if validation messages become annoying during setup. Only runs in Editor, does not affect runtime performance.
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
StateSettings are shared between vehicles of the same type. Create different StateSettings for different vehicle categories (sports car, truck, etc.) or performance targets (mobile, PC). Right-click in Project > Create > NWH Vehicle Physics > State Settings to create new 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
Current distance in meters between the vehicle and the LOD camera. Updated every 0.2 seconds during LOD checks.
Declaration
[NonSerialized]
[Tooltip("Distance between camera and vehicle used for determining LOD.")]
public float vehicleToCamDistance
Field Value
| Type | Description |
|---|---|
| float |
Remarks
Use this value for debugging or custom distance-based logic. Lower values mean the vehicle is closer to the camera.
wheelbase
Distance between front and rear axles in meters. Automatically calculated for standard 4-wheel vehicles.
Declaration
[Tooltip(" Valid only for 4-wheeled vehicles with 2 axles (i.e. cars).\r\n For other vehicles this value will be 0.")]
public float wheelbase
Field Value
| Type | Description |
|---|---|
| float |
Remarks
Only valid for 4-wheeled vehicles with 2 axles. Returns 0 for other configurations. Used for weight transfer calculations and vehicle dynamics. Typical values: Compact car (2.4-2.6m), Sedan (2.7-2.9m), SUV (2.8-3.2m).
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
This list is populated during initialization and should not be modified directly. Use ModuleManager to add/remove modules at runtime.
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
Returns false during Awake() and early Start(). Returns true after onVehicleInitialized event. Accessing vehicle components when this is false may result in NullReferenceExceptions.
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
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 |
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 |
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
Called automatically when the component is first added or when Reset is selected in the Inspector. Default resources are loaded from 'NWH Vehicle Physics 2/Defaults/' in Resources folder. Override this method to provide custom default configurations.
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
Automatically disables autoSetInput to prevent local input from overriding network state. Light states, engine RPM, and all input values are synchronized.
Update()
Declaration
public virtual void Update()
UpdateComponentLODs()
Updates the LOD state of all vehicle components based on the current LOD level. Components are enabled/disabled according to their LOD index settings.
Declaration
protected virtual void UpdateComponentLODs()
Remarks
Called after LOD level changes. Each component's LOD index determines at which LOD levels it remains active. Components with LOD index -1 ignore the LOD system.
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()