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.
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.
To integrate an external input provider, we need to:
DemoVehicleControllerOriginal 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:
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; }
Remove Direct Input Reads: Remove or comment out code that directly reads player input (e.g., Input.GetAxis statements).
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;