Documentation: Creating an Input Provider for a Custom Vehicle Controller in Unity

This guide provides a step-by-step approach to creating an input provider for a custom vehicle controller in Unity, allowing flexible and modular handling of player inputs. We’ll use the DemoVehicleController and DemoInputProvider as references and modify a custom vehicle controller to integrate with an input provider.

Overview

The objective is to decouple direct input handling from the vehicle controller, using an input provider instead. This structure enables modular control, where the vehicle controller can accept inputs from different sources (e.g., AI, player, or a custom input system) without modifying the core vehicle code/logic.

Prerequisites

Steps

1. Modify the Vehicle Controller Script

To integrate an external input provider, we need to:

  1. Remove direct input settings within the vehicle controller (if they exist).
  2. Allow the controller to receive inputs (such as acceleration, steering, and handbrake) from an external provider.

Example: Modifying DemoVehicleController

Original Input Handling in Vehicle Controller

In some vehicle controller scripts, input handling (like reading the player's horizontal or vertical axis) is embedded directly. This setup limits flexibility since inputs are tied to player controls.

Required Changes

To integrate an input provider, follow these changes:

  1. Expose Input Fields: Define public properties or fields for accelerationInput, steeringInput, and handbrakeInput so they can be set externally.

    Example:

    public float AccelerationInput { get; set; }
    public float SteeringInput { get; set; }
    public float HandbrakeInput { get; set; }
    
  2. Remove Direct Input Reads: Remove or comment out code that directly reads player input (e.g., Input.GetAxis statements).

  3. Use External Inputs: In your vehicle controller’s Update or FixedUpdate method, replace internal input values with the exposed input properties.

    // example Old direct input usage
    // float steer = Input.GetAxis("Horizontal");
    // float acceleration = Input.GetAxis("Vertical");
    
    // Updated to use external inputs
    float steer = SteeringInput;
    float acceleration = AccelerationInput;