Wie wechsle ich in meinem Unity Spiel von dem Alten zum Neuen input system? erkläre es mir schritt für schritt
Assistant
Um von dem alten zum neuen Input-System in Unity zu wechseln, befolgen Sie bitte die untenstehenden Schritte. Beachten Sie, dass diese Anweisungen für Projekte gelten, die bereits mit dem alten Input-System erstellt wurden und in denen Sie nun auf das neue Input-System umsteigen möchten.
Unity-Version überprüfen:
Stellen Sie zuerst sicher, dass Sie eine Unity-Version verwenden, die das neue Input-System unterstützt (Unity 2019.1 oder höher).
Neues Input-System installieren:
Öffnen Sie das Unity-Projekt.
Gehen Sie zum Menü Window > Package Manager.
Suchen Sie in der Liste der verfügbaren Pakete nach "Input System".
Klicken Sie auf das Paket und dann auf die Schaltfläche "Install" oder "Update", um die neueste Version des neuen Input-Systems zu installieren.
Input-System-Einstellungen anpassen:
Nach der Installation müssen Sie Unity mitteilen, dass das neue System verwendet werden soll.
Gehen Sie zu Edit > Project Settings > Player.
Wählen Sie im Abschnitt "Other Settings" unter "Active Input Handling" die Option "Input System Package (New)" aus.
Unity fragt Sie, ob Sie das Projekt neu laden möchten. Bestätigen Sie dies, damit die Änderungen wirksam werden.
Alte Input-Konfigurationen entfernen:
Wenn Sie vorher InputManager-Assets (InputManager.asset) und Skripte verwendet haben, die das alte Unity Input-System (UnityEngine.Input) verwenden, dann müssen Sie diese Skripte überarbeiten und können die alten Input-Manager-Assets entfernen, sobald Sie sie nicht mehr benötigen.
Skripte auf das neue Input-System umstellen:
Öffnen Sie die Skripte, die das alte Input-System verwenden und aktualisieren Sie diese, um das neue Input-System-API zu verwenden.
Sie werden statt Input jetzt die Namensräume UnityEngine.InputSystem oder InputSystem verwenden.
Input-Actions erstellen:
Das neue Input-System verwendet ein "Action-based" System anstelle von direktem Polling von Tasten und Achsen.
Erstellen Sie ein Input Action Asset, indem Sie mit der rechten Maustaste in den Project-Browser klicken, dann Create > Input Actions wählen.
Öffnen Sie das neu erstellte Input Action Asset und konfigurieren Sie Ihre Input-Actions (z. B. Bewegung, Springen, Schießen).
Input-Actions in Skripten verwenden:
Binden Sie Ihr Input Action Asset in Ihr Skript ein und reagieren Sie auf Trigger-Ereignisse der definierten Actions.
Testen und Debuggen:
Testen Sie Ihr Spiel, um sicherzustellen, dass alle Eingaben korrekt funktionieren. Das neue Input-System bietet auch ein Input-Debugger-Fenster, das Ihnen helfen kann, Eingabeereignisse zu beobachten und Fehler zu finden.
Diese Schritte bieten eine grundlegende Anleitung zum Wechsel vom alten zum neuen Input-System. Die konkreten Änderungen in den Skripten hängen von Ihrer spezifischen Implementierung und den genutzten Inputs ab. Es kann auch notwendig sein, zusätzliche Arbeiten an der Benutzerführung und an der Anpassung des UI-Verhaltens vorzunehmen, sodass diese mit dem neuen Input-System kompatibel sind.
User
Ich werde dir nun meinen code mit dem alten input system zeigen, und du wirst mir bitte sagen was ich genau machen muss um das neue input system zu implementieren
Assistant
Gerne können Sie mir Ihren aktuellen Unity-Code zeigen, der das alte Input-System verwendet. Anschließend werde ich Ihnen beispielhaft erklären, wie Sie ihn auf das neue Input-System umstellen können. Bitte teilen Sie mir den betreffenden Code-Abschnitt mit.
User
using System.Collections.Generic;
using CustomInspector;
using Mirror;
using UI;
using UnityEngine;
using static Prometeo.CarController;
namespace PlayerBehaviour
{
public class PlayerDriveController : DriveController
{
public PlayerDriveController() : base(Activation.LocalAndServer) { }
code
protected override void Update()
{
base.Update();
if (Input.GetKeyDown(KeyCode.LeftShift))
{
SendNitro();
}
}
Acceleration prevAcceleration = Acceleration.Neutral;
Steering prevSteering = Steering.Straight;
bool prevBrake = false;
[ClientCallback]
public void FixedUpdate()
{
if (!isLocalPlayer) return;
var currentAcceleration = Acceleration.Neutral;
if (Input.GetKey(KeyCode.W) && !Input.GetKey(KeyCode.S))
currentAcceleration = Acceleration.Positive;
if (Input.GetKey(KeyCode.S) && !Input.GetKey(KeyCode.W))
currentAcceleration = Acceleration.Negative;
var currentSteering = Steering.Straight;
if (Input.GetKey(KeyCode.D) && !Input.GetKey(KeyCode.A))
currentSteering = Steering.Right;
if (Input.GetKey(KeyCode.A) && !Input.GetKey(KeyCode.D))
currentSteering = Steering.Left;
var currentBrake = Input.GetKey(KeyCode.Space);
if (currentAcceleration != prevAcceleration
|| currentSteering != prevSteering
|| currentBrake != prevBrake)
{
prevAcceleration = currentAcceleration;
prevSteering = currentSteering;
prevBrake = currentBrake;
SendNewInput(motor: currentAcceleration, steering: currentSteering, handbrake: currentBrake);
}
}
}
[System.Serializable]
public class AxleInfo
{
public WheelCollider leftWheel;
public WheelCollider rightWheel;
public bool motor;
public bool steering;
}
}
Brauchst du noch weiteren code? (für das car movement)
Assistant
Um das neue Input System von Unity zu verwenden, müssen Sie einige Schritte durchführen, um Ihren bestehenden Code umzuschreiben. Ihrer Beschreibung nach zu urteilen, scheint Ihr Spiel ein Rennspiel zu sein, in dem Tastendrücke verwendet werden, um ein Auto zu steuern.
Hier die Schritte, um den gezeigten Code auf das neue Input-System umzustellen:
Aktivieren Sie das neue Input-System wie in meinem vorherigen Beitrag beschrieben.
Erstellen Sie ein Input Actions Asset, um Ihre Steueraktionen zu definieren. Dies tun Sie im Unity Editor:
Rechtsklick im Projektfenster und wählen Sie Create > Input Actions.
Öffnen Sie die neu erstellte Input Actions Datei.
Definieren Sie Aktionen für "Acceleration", "Steering" und "Nitro", und binden Sie sie an entsprechende Tasten (W, A, S, D, Left Shift, Space).
Referenzieren Sie das Input Actions Asset in Ihrem Skript. Erstellen Sie dazu ein Feld im PlayerDriveController-Klasse, um das erstellte Input Actions Asset zu referenzieren.
Initialisieren Sie die Input Actions im Code. Hierzu müssen Sie das Input Actions Asset laden, aktivieren und die entsprechenden Callbacks einrichten.
Hier ist ein Beispiel, wie Ihr umgeschriebener PlayerDriveController aussehen könnte (bitte beachten Sie, dass die Namen Ihrer Input Actions denen im erstellten Input Actions Asset entsprechen müssen):
csharp
User
using UnityEngine;
using UnityEngine.UI;
using Mirror;
using System;
using CustomInspector;
using System.Linq;
To implement the new Unity Input System while retaining the existing functionality of your PlayerDriveController class, you'll need to follow the below steps. I'll provide the complete PlayerDriveController script based on your provided code. Please ensure you have already created an Input Actions Asset and defined the necessary actions as described in previous messages.
First, define an InputActions class to map our actions:
Show me the complete PlayerDriveController code please
Assistant
Certainly! Here is the complete PlayerDriveController script, adapted to work with the new Unity Input System. This script assumes that input actions for Acceleration, Steering, and Handbrake have been defined in an Input Actions Asset. This script also assumes that the necessary public properties or methods have been added to CarController to externally set acceleration, steering, and handbrake status.
Please note that you will need to connect the PlayerInput component in the inspector for this script to work properly, and that the actual update of the car may need to happen in the Update or FixedUpdate of your CarController.
csharp
User
You have my carcontroller script. Why are you saying "if thats in the carcontroller.. if your carcontroller script does this..." as if you dont know
Assistant
My apologies for any confusion. In this case, based on the CarController you've provided, we need to adapt the PlayerDriveController to pass input from the new Input System to the relevant methods or properties in the CarController.
Let's attempt to create the adapted PlayerDriveController with the assumption that we've exposed public methods in CarController to handle updating the acceleration, steering, and braking actions as expected:
csharp
User
couldnt find PlayerInputActions
Assistant
I apologize for the confusion earlier. The PlayerInputActions class I mentioned before was intended to represent the C# class that gets automatically generated by Unity's Input System when you create an Input Actions Asset, which I incorrectly referred to.
Instead, Unity's Input System uses the "Input Actions Editor" to create a .inputactions asset file, and from this file, you can generate a C# class. Here's what you'll need to do if you haven't already:
Open the Input Actions window in Unity by navigating to Window > Asset Management > Input System > Input Actions.
In this window, create your input actions and maps (such as "Accelerate", "Steer", "Brake").
Make sure to save the asset in your project.
With the asset still open in the Input Actions Editor, click the "Generate C# Class" button at the bottom of the window (ensure the "Generate C# Class" option is checked).
This will create a C# script with a class inside, typically with the same name as your .inputactions asset file, but formatted in PascalCase. For example, if your .inputactions asset was named "PlayerInput", the generated script might by default contain a class named PlayerInput.
Here is an updated PlayerDriveController that utilizes the new Unity Input System using the generated C# class from the last step above:
csharp
User
CarController is NOT on the player car gameobject. Btw, here is the DriveController Script. it is initialised through auto-fill in a CarData script:
using CustomInspector;
using Mirror;
using PlayerBehaviour;
using Prometeo;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DriveController : NetworkEnabled
{
public DriveController(Activation activation = Activation.LocalAndServer) : base(activation) { }
code
Assistant
Based on your CarController script that is not located on the player car GameObject, and the provided DriveController script which handles input and network synchronization using Mirror, here's how you could implement the PlayerDriveController:
First, we don't need to create a new PlayerInputActions as Unity generates this for us based on our Input Actions Asset. Then, we get the PlayerInput component which is attached on the player car GameObject and listen to its input events.
Here is the adjusted PlayerDriveController script implementing the new Unity Input System with Mirror for network synchronization. You'll need to provide the appropriate Unity-generated input class name where it says <YourInputActionsClassName>:
csharp
User
bro playerdrivecontroller is not NetworkBehavior. It inherits from DriveController
Assistant
Apologies for the oversight. Here is a revised version of the PlayerDriveController script that inherits from DriveController.
This version assumes you have set up your input actions for acceleration, steering, braking, and nitro in the Input Actions Asset. It also assumes that the SendNewInput and other methods are correctly implemented in DriveController to handle communication between PlayerDriveController and CarController.
Please ensure that the names of the input actions in the script match exactly with those defined in your Input Actions Asset.
csharp
User
using System.Collections.Generic;
using CustomInspector;
using Mirror;
using UI;
using UnityEngine;
using static Prometeo.CarController;
namespace PlayerBehaviour
{
public class PlayerDriveController : DriveController
{
public PlayerDriveController() : base(Activation.LocalAndServer) { }
code
protected override void Update()
{
base.Update();
if (Input.GetKeyDown(KeyCode.LeftShift))
{
SendNitro();
}
}
Acceleration prevAcceleration = Acceleration.Neutral;
Steering prevSteering = Steering.Straight;
bool prevBrake = false;
[ClientCallback]
public void FixedUpdate()
{
if (!isLocalPlayer) return;
var currentAcceleration = Acceleration.Neutral;
if (Input.GetKey(KeyCode.W) && !Input.GetKey(KeyCode.S))
currentAcceleration = Acceleration.Positive;
if (Input.GetKey(KeyCode.S) && !Input.GetKey(KeyCode.W))
currentAcceleration = Acceleration.Negative;
var currentSteering = Steering.Straight;
if (Input.GetKey(KeyCode.D) && !Input.GetKey(KeyCode.A))
currentSteering = Steering.Right;
if (Input.GetKey(KeyCode.A) && !Input.GetKey(KeyCode.D))
currentSteering = Steering.Left;
var currentBrake = Input.GetKey(KeyCode.Space);
if (currentAcceleration != prevAcceleration
|| currentSteering != prevSteering
|| currentBrake != prevBrake)
{
prevAcceleration = currentAcceleration;
prevSteering = currentSteering;
prevBrake = currentBrake;
SendNewInput(motor: currentAcceleration, steering: currentSteering, handbrake: currentBrake);
}
}
}
[System.Serializable]
public class AxleInfo
{
public WheelCollider leftWheel;
public WheelCollider rightWheel;
public bool motor;
public bool steering;
}
}
This is the old code. it doesnt need to initialize the carcontroller. Why does the new one? Make it possible without getting the actual component. use the static functions
Assistant
I understand that you want to retain the structure of your original PlayerDriveController script and avoid directly interacting with the CarController component. In the updated version of your PlayerDriveController script, we'll access the input through the new Unity Input System but maintain the logic as per the existing structure.
To use Unity's new Input System, you first need to create an Input Action Asset if you haven't already. With the Input Action Asset defined and the C# class generated, we will only need to reference the Input Actions instead of the CarController component.
Here's the updated PlayerDriveController script that utilizes the Unity Input System and keeps the same logic as the old script:
csharp
User
Please add the logic for acc, steering,... this is how it looks in the old script.
using System.Collections.Generic;
using CustomInspector;
using Mirror;
using UI;
using UnityEngine;
using static Prometeo.CarController;
namespace PlayerBehaviour
{
public class PlayerDriveController : DriveController
{
public PlayerDriveController() : base(Activation.LocalAndServer) { }
protected override void Update()
{
base.Update();
if (Input.GetKeyDown(KeyCode.LeftShift))
{
SendNitro();
}
}
[System.Serializable]
public class AxleInfo
{
public WheelCollider leftWheel;
public WheelCollider rightWheel;
public bool motor;
public bool steering;
}
}
Assistant
Great, given the logic you provided, I'll integrate that logic with Unity's new Input System. You will no longer use Input.GetKey to check the key states; instead, it should be done via the Input Actions you have set up.
Here is your updated PlayerDriveController script using the new Input System:
csharp
User
When i press W or S, the car goes full speed acceleration and i cant stop it. When I press A or D, the car turns to the right and i can never stop it
Assistant
The issue you're encountering likely stems from the fact that the input values are being read once during the initial trigger (performed event) and aren't updated or reset appropriately when the keys are released. To address this, make sure that the canceled events are correctly resetting the acceleration and steering when the keys are released.
Here's an adjusted segment of your PlayerDriveController script that handles both performed and canceled events to ensure it handles starting and stopping of input actions correctly:
okay the cancel works. however, steering left doesnt work. when i press A it also steers to the right. As well as Reversing (S). when i press s it accelerates
Assistant
If pressing 'A' results in steering to the right (similar to pressing 'D') and pressing 'S' results in acceleration (similar to pressing 'W'), it suggests that the values being read from the input actions might not be handling negative values or might be hardcoded to a certain direction. You must ensure that the actions are configured correctly in the Input Actions Asset to handle both positive and negative values, as key or button presses will only return 1 (pressed) or 0 (not pressed), whereas joystick or gamepad thumbstick will return values in a range from -1 to 1.
Let's review and fix the OnSteer and OnAccelerate methods, making sure they properly handle negative values for both steering and acceleration:
csharp
private void OnAccelerate(float value)
{
// Handle positive and negative values appropriately for acceleration/reverse.
currentAcceleration = value switch
{
> 0 => Acceleration.Positive, // Forward
< 0 => Acceleration.Negative, // Reverse
_ => Acceleration.Neutral // No Input
};
UpdateInput();
}
private void OnSteer(float value)
{
// Handle positive and negative values appropriately for left/right steering.
currentSteering = value switch
{
> 0 => Steering.Right,
< 0 => Steering.Left,
_ => Steering.Straight // No Input
};
UpdateInput();
}
Make sure your input actions for steering and acceleration are configured to correctly handle the directional inputs, e.g., 'A' should return a negative value and 'S' might also return a negative value for reverse:
Open your Input Actions Asset in Unity.
Find the "Steer" action and ensure it is set up to return a value from -1 (full left) to 1 (full right) with type "Value" and control type as "Stick" or another appropriate type depending on your input device. If you're using keys, you'll have to map 'A' to -1 and 'D' to 1, typically with a "Composite" binding where you set up "Negative" and "Positive" paths.
Similarly, for the "Accelerate" action, make sure that it's set up to return a value from -1 (reverse) to 1 (forward).
Ensure you save your Input Action Asset after making any changes and that the corresponding C# script is regenerated if needed.
If you are using a custom script to handle input rather than the generated C# class from the Input Actions Asset, check to ensure you aren't inadvertently converting negative values to positive ones anywhere in the input handling code.
User
using CustomInspector;
using Mirror;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.VFX;
namespace PlayerBehaviour
{
public class PlayerShooting : Shooting
{
public PlayerShooting() : base(Activation.Local) { }
code
private float shootBlock;
protected override void Start()
{
base.Start();
if (!isLocalPlayer)
this.enabled = false;
}
[ClientCallback]
void Update()
{
if (!isLocalPlayer)
return;
if (shootBlock <= 0)
{
if (Input.GetKey(KeyCode.Mouse0) && InGameMouse.IsLocked)
{
shootBlock = weaponStats.FireDelay;
if (weaponStats.FireDelay > .5f)
ReloadingBar.DisplayReload(weaponStats.FireDelay);
carData.CameraController.ShootEffect();
PushbackOnCar();
ClientShoot(Emitter.position);
}
}
else
{
shootBlock -= Time.deltaTime;
}
[Client]
void ClientShoot(Vector3 position)
{
position += Emitter.forward * .25f; //some space forward to fix hitting itself
if (Physics.Raycast(position, Emitter.forward, out RaycastHit hit, 1000))
{
if (hit.collider.CompareTag(Tags.Names.Player.ToString()))
{
NetworkIdentity others = hit.collider.attachedRigidbody.GetComponentOrFail<NetworkIdentity>();
if (others.netId == this.netId)
{
// Hit myself - continue from thereon
ClientShoot(hit.point);
return;
}
CmdHitOtherPlayer(others.netId);
}
CmdShootEffect(position, hit.point, hit.normal);
}
else
CmdShootEffect(position, position + Emitter.forward * 100, Emitter.forward);
}
}
[Command]
void CmdHitOtherPlayer(uint netId) => SvrHitOtherPlayer(netId);
[Command]
void CmdShootEffect(Vector3 start, Vector3 end, Vector3 normal) => SvrShootEffect(start, end, normal);
}
}
This is my old PlayerShooting script. I want to implement the new input system here also. i tried to do it but it didnt really work
Assistant
To convert your existing PlayerShooting script to use the new Unity Input System, you'll need to follow similar steps as before: set up your input actions in the Input Actions Asset, generate the C# class, and then use these actions in your script.
Assuming you have set up an input action called "Shoot" in your Input Actions Asset and generated the corresponding C# class, here's how you can adapt your PlayerShooting script:
csharp
using CustomInspector;
using Mirror;
using System;
using UnityEngine;
using UnityEngine.InputSystem; // Required namespace
namespace PlayerBehaviour
{
public class PlayerShooting : Shooting
{
// Your existing code...
private PlayerControls playerControls; // Assuming PlayerControls is the generated class name
private void Awake()
{
base.Awake();
playerControls = new PlayerControls();
}
private void OnEnable()
{
playerControls.Enable();
playerControls.Player.Shoot.performed += OnShootPerformed;
playerControls.Player.Shoot.canceled += OnShootCanceled;
}
private void OnDisable()
{
playerControls.Player.Shoot.performed -= OnShootPerformed;
playerControls.Player.Shoot.canceled -= OnShootCanceled;
playerControls.Disable();
}
// Called when the Shoot action is performed
private void OnShootPerformed(InputAction.CallbackContext context)
{
if (!isLocalPlayer || !InGameMouse.IsLocked)
return;
// The logic inside here is based on your original Input.GetKey(KeyCode.Mouse0) condition
if (shootBlock <= 0)
{
shootBlock = weaponStats.FireDelay;
if (weaponStats.FireDelay > .5f)
ReloadingBar.DisplayReload(weaponStats.FireDelay);
carData.CameraController.ShootEffect();
PushbackOnCar();
ClientShoot(Emitter.position);
}
}
// Called when the Shoot action is canceled (e.g., mouse button released)
private void OnShootCanceled(InputAction.CallbackContext context)
{
// Handle shoot cancellation if needed
}
[ClientCallback]
void Update()
{
if (!isLocalPlayer)
return;
// Update shootBlock cooldown timer
if (shootBlock > 0)
{
shootBlock -= Time.deltaTime;
}
}
// Rest of your methods...
}
}
User
Why do you call the functions in onEnabled and onDisabled? Previously, you called them in Awake()
Assistant
You're right; my mistake. Event subscriptions to Unity Input System actions are commonly done in Awake() or OnEnable() depending on when you want to start listening to the events and when the Input System is set up.
The reason to consider OnEnable() and OnDisable() is for robustness around the object activation lifecycle. If the GameObject that the script is attached to gets disabled and then enabled again during the gameplay, you would want to re-subscribe to the input actions upon re-enabling to ensure they keep working.
Subscribing in Awake() means the subscriptions will occur as the object is being initialized, which is just once when the object is created or loaded. If your script should only subscribe once and the GameObject is not going to be enabled/disabled during the game, then Awake() is suitable. On the other hand, if the GameObject may be enabled/disabled, then OnEnable()/OnDisable() ensure the script always listens to input actions appropriately while it is active.
Here's an updated approach using Awake():
csharp
using UnityEngine;
using UnityEngine.InputSystem;
namespace PlayerBehaviour
{
public class PlayerShooting : Shooting
{
private PlayerControls playerControls;
public PlayerShooting() : base(Activation.Local) { }
protected override void Awake()
{
base.Awake();
playerControls = new PlayerControls();
// Subscribe to the actions in Awake, if the GameObject is not going to be disabled/enabled often
playerControls.Player.Shoot.performed += OnShootPerformed;
playerControls.Player.Shoot.canceled += OnShootCanceled;
}
private void OnEnable()
{
playerControls.Enable(); // Make sure to enable the input when the object is active
}
private void OnDisable()
{
// If we subscribe in Awake, we still need to disable the input when the object is not active
playerControls.Disable();
}
// ... rest of your code with OnShootPerformed and OnShootCanceled methods
}
}
By subscribing in Awake() and enabling/disabling the input system in OnEnable()/OnDisable(), you ensure that your script starts listening to input actions as soon as it's initialized and properly manages action enabling based on the GameObject's active state. Remember to unsubscribe in OnDisable() or OnDestroy() to prevent potential memory leaks or unexpected behavior if you ever destroy the GameObject.
User
Thank you. it worked, but still has a flaw. When i hold the mouse button down, it should keep firing. However in this case, you can only shoot manually by pressing it over and over again
Assistant
The Input System's "Performed" and "Canceled" events are designed to handle state changes, such as when an action starts or stops. If you want to simulate holding down a button and having something happen repeatedly—as with automatic weapon fire—you need to check the state of the action within the Update method. This allows you to continuously check if the input is being held down and perform an action based on that.
First, define a boolean in your PlayerShooting class to track whether the shoot button is currently being held:
csharp
private bool isShooting = false;
Then, modify the OnShootPerformed and OnShootCanceled methods to set this boolean appropriately:
Within your Update method, you handle the automatic firing logic using the isShooting boolean:
csharp
[ClientCallback]
void Update()
{
if (!isLocalPlayer)
return;
if (isShooting && shootBlock <= 0)
{
shootBlock = weaponStats.FireDelay;
if (weaponStats.FireDelay > .5f)
ReloadingBar.DisplayReload(weaponStats.FireDelay);
carData.CameraController.ShootEffect();
PushbackOnCar();
ClientShoot(Emitter.position);
// If fire rate is instant, reset isShooting to allow for next shot
if (weaponStats.FireRate == 0)
{
isShooting = false;
}
}
else if (shootBlock > 0)
{
shootBlock -= Time.deltaTime;
}
}
Make sure weaponStats.FireRate or weaponStats.FireDelay is configured to control the rate of fire properly. With this setup, every frame Update checks if isShooting is true and if the cooldown (shootBlock) allows for another shot. If so, it fires another shot and resets the cooldown.
Remember that with this setup, if the fire rate is really fast (i.e., automatic fire), the Update method can call ClientShoot multiple times very quickly, which can overwhelm the server or network with commands. You might need to fine-tune the firing rate and consider using FixedUpdate for consistent timing, depending on your game's needs.
User
How do I get use the live Mouse X axis and Y axis in the new input system? I have created actions in the map
Assistant
To access the live mouse X and Y axis values in the new Unity Input System, you'll first need to ensure that you've set up Actions for them in your Input Actions Asset. Typically, these would be 1D axis actions that map to the mouse's delta movement.
Here's how you can create these actions:
Open the Input Actions window with Window > Asset Management > Input System > Input Actions.
Create a new action map or use an existing one, for example, named "Player".
Inside this action map, create two actions: "MouseX" and "MouseY".
Assign the Mouse -> Delta -> X path to "MouseX" and Mouse -> Delta -> Y to "MouseY".
Save the asset.
This should generate the C# class for the actions after you've clicked the "Generate C# Class" button. Once you have the class, you can use it to subscribe to the mouse axis movements.
Here's a sample script on how to use the mouse X and Y axis in your game:
csharp
using UnityEngine;
using UnityEngine.InputSystem;
public class MouseLook : MonoBehaviour
{
private PlayerControls playerControls; // Replace with the generated Input System class name
private Vector2 mouseDelta;
private void Awake()
{
playerControls = new PlayerControls(); // Initialize the PlayerControls
// Subscribing to the action's performed event to get the values
playerControls.Player.MouseX.performed += ctx => mouseDelta.x = ctx.ReadValue<float>();
playerControls.Player.MouseY.performed += ctx => mouseDelta.y = ctx.ReadValue<float>();
}
private void OnEnable()
{
playerControls.Enable(); // Enable the input actions
}
private void OnDisable()
{
playerControls.Disable(); // Disable the input actions
}
private void Update()
{
// Use mouseDelta here for rotating your camera or character
// Example: transform.Rotate(Vector3.up * mouseDelta.x);
// After processing the input, reset the delta to 0
mouseDelta = Vector2.zero;
}
}
using UnityEngine;
using UnityEngine.InputSystem; // Neuer Namespace für das neue Input-System
namespace PlayerBehaviour
{
public class PlayerDriveController : DriveController
{
[SerializeField]
private InputActionAsset inputActionAsset; // Referenz auf das Input Action Asset
// Referenzen auf spezifische Input Actions
private InputAction nitroAction;
private InputAction accelerationAction;
private InputAction steeringAction;
private InputAction brakeAction;
public PlayerDriveController() : base(Activation.LocalAndServer) { }
private void OnEnable()
{
// Lade die Aktionen und aktiviere sie
nitroAction = inputActionAsset.FindAction("Nitro");
accelerationAction = inputActionAsset.FindAction("Acceleration");
steeringAction = inputActionAsset.FindAction("Steering");
brakeAction = inputActionAsset.FindAction("Brake");
nitroAction.performed += ctx => SendNitro(); // Binden des Events an den Callback
nitroAction.Enable();
accelerationAction.Enable();
steeringAction.Enable();
brakeAction.Enable();
}
private void OnDisable()
{
// Deaktiviere die Aktionen, wenn das Objekt deaktiviert wird
nitroAction.Disable();
accelerationAction.Disable();
steeringAction.Disable();
brakeAction.Disable();
}
[ClientCallback]
public void FixedUpdate()
{
if (!isLocalPlayer) return;
var currentAcceleration = accelerationAction.ReadValue<float>(); // Diese Methode gibt einen Wert zwischen -1 und 1 zurück
var currentSteering = steeringAction.ReadValue<float>(); // Diese Methode gibt einen Wert zwischen -1 und 1 zurück
var currentBrake = brakeAction.triggered; // Dies gibt true zurück, wenn die Bremse (Space) gedrückt wird
// Führen Sie hier Ihre Logik zur Umwandlung von Float-Werten in Ihre Acceleration- und Steering-Enumerationen durch
/* Code zum Senden von Steuersignalen */
}
}
}
Implementieren Sie Ihre Logik, um currentAcceleration und currentSteering in die entsprechenden Enumerationswerte zu konvertieren. Wenn Ihr Spiel eine analoge Steuerung unterstützt, können Sie die Float-Werte direkt verwenden, um eine proportionale Steuerung zu ermöglichen. Falls Sie eine digitale (Ein/Aus) Steuerung haben, möchten Sie vielleicht eine Konversion basierend auf einem Schwellwert durchführen.
Testen Sie Ihr Spiel, um sicherzustellen, dass alle Änderungen korrekt funktionieren.
Bitte beachten Sie, dass dieser code nur ein Beispiel ist und entsprechend den genauen Namen der definierten Input Actions angepasst werden muss. Ebenfalls muss die Logik zur Umwandlung von Float-Werten in Ihre spezifischen Enumerationswerte implementiert werden.
#if UNITY_EDITOR
[SerializeField, ShowIf(StaticConditions.IsNotPlaying), Button(nameof(Editor_TryFindGameObjects), tooltip = "If wheels are null, it tries to find them by name: .bl, .br, .fr and .fl", size = Size.small), HideField] bool _;
void Editor_TryFindGameObjects()
{
var children = this.transform.GetAllChildrenRecursively();
code
//Meshes in 'wheels'
Transform wheelsHolder = children.FirstOrDefault(child => child.name == "Wheels");
if (wheelsHolder == null)
{
Debug.LogError("No gameobject 'Wheels' found");
return;
}
children = wheelsHolder.GetAllChildrenRecursively();
if (frontLeftMesh == null)
frontLeftMesh = children.FirstOrDefault(child => child.name.Contains(".fl")).gameObject;
if (frontRightMesh == null)
frontRightMesh = children.FirstOrDefault(child => child.name.Contains(".fr")).gameObject;
if (rearLeftMesh == null)
rearLeftMesh = children.FirstOrDefault(child => child.name.Contains(".bl")).gameObject;
if (rearRightMesh == null)
rearRightMesh = children.FirstOrDefault(child => child.name.Contains(".br")).gameObject;
//Collider in 'WheelCollider'
wheelsHolder = children.FirstOrDefault(child => child.name == "WheelCollider");
if (wheelsHolder == null)
{
Debug.LogError("No gameobject 'WheelCollider' found");
return;
}
children = wheelsHolder.GetAllChildrenRecursively();
if (frontLeftCollider == null)
frontLeftCollider = children.FirstOrDefault(child => child.name.Contains(".fl")).GetComponentOrFail<WheelCollider>();
if (frontRightCollider == null)
frontRightCollider = children.FirstOrDefault(child => child.name.Contains(".fr")).GetComponentOrFail<WheelCollider>();
if (rearLeftCollider == null)
rearLeftCollider = children.FirstOrDefault(child => child.name.Contains(".bl")).GetComponentOrFail<WheelCollider>();
if (rearRightCollider == null)
rearRightCollider = children.FirstOrDefault(child => child.name.Contains(".br")).GetComponentOrFail<WheelCollider>();
}
#endif
}
}
This is the logic. it gets referenced in my PlayerDriveController script that i showed you. Show me the complete PlayerDriveController script that implements the new input system but hasthe exact same functionality as the old script
Attach the PlayerInputActions component to the same GameObject where your PlayerDriveController is.
Now, we'll update the PlayerDriveController script to subscribe to these actions, and control the car based on the input:
csharp
using Mirror;
using UnityEngine;
using Prometeo; // Ensure your namespace is correct
namespace PlayerBehaviour
{
public class PlayerDriveController : NetworkBehaviour // Assuming you're using Mirror for networking
{
// We'll use SerializeField to allow you to link the CarController in the inspector.
[SerializeField] private CarController carController;
private PlayerInputActions inputActions;
// Start method for initial setup
private void Start()
{
if (!isLocalPlayer) return;
inputActions = GetComponent<PlayerInputActions>();
if (inputActions == null)
Debug.LogError("PlayerInputActions component is required on the GameObject.");
// Subscribe to input events
inputActions.OnAcceleration += HandleAcceleration;
inputActions.OnSteering += HandleSteering;
inputActions.OnHandbrake += HandleHandbrake;
}
private void OnDestroy()
{
if (inputActions != null)
{
// Unsubscribe from input events
inputActions.OnAcceleration -= HandleAcceleration;
inputActions.OnSteering -= HandleSteering;
inputActions.OnHandbrake -= HandleHandbrake;
}
}
private void HandleAcceleration(float value)
{
// Implement the logic here to control the car's acceleration.
// Convert value from [-1, 1] to your Acceleration enum as needed.
if (value > 0)
carController.currentAcceleration = CarController.Acceleration.Positive;
else if (value < 0)
carController.currentAcceleration = CarController.Acceleration.Negative;
else
carController.currentAcceleration = CarController.Acceleration.Neutral;
// Call relevant methods in carController based on the value of currentAcceleration
}
private void HandleSteering(float value)
{
// Implement the logic here to control the car's steering.
// Convert value from [-1, 1] to your Steering enum as needed.
if (value > 0)
carController.currentSteering = CarController.Steering.Right;
else if (value < 0)
carController.currentSteering = CarController.Steering.Left;
else
carController.currentSteering = CarController.Steering.Straight;
// Call relevant methods in carController based on the value of currentSteering
}
private void HandleHandbrake(bool isHandbrakeOn)
{
// Apply handbrake logic based on isHandbrakeOn
carController.CurrentHandbrake = isHandbrakeOn;
// If handbrake logic directly affects CarController methods, call them here
}
// Update and FixedUpdate methods are not needed anymore,
// since we're using events to handle inputs now.
}
}
Remember to replace the calls to carController methods with actual methods that handle the car's movement, braking, and steering based on the input. You will have to ensure that CarController has public methods or properties that can be controlled externally, as direct access to currentSteering, currentAcceleration, and currentHandbrake may not be appropriate.
Please also make sure to connect the PlayerInputActions component in the inspector and configure your input actions accordingly via the Input Actions Asset. This will require some adjustments based on your specific game logic, but the structure provided here should guide you through the transition.
using UnityEngine;
using UnityEngine.InputSystem;
namespace PlayerBehaviour
{
public class PlayerDriveController : MonoBehaviour
{
public CarController carController;
private PlayerInput playerInput;
private InputAction moveAction;
private InputAction steerAction;
private InputAction brakeAction;
private void Awake()
{
// Assuming CarController is on the same GameObject
if (carController == null)
carController = GetComponent<CarController>();
playerInput = GetComponent<PlayerInput>();
moveAction = playerInput.actions["Acceleration"];
steerAction = playerInput.actions["Steering"];
brakeAction = playerInput.actions["Handbrake"];
}
private void OnEnable()
{
moveAction.Enable();
steerAction.Enable();
brakeAction.Enable();
moveAction.performed += OnAccelerationPerformed;
moveAction.canceled += OnAccelerationCanceled;
steerAction.performed += OnSteeringPerformed;
steerAction.canceled += OnSteeringCanceled;
brakeAction.performed += OnBrakePerformed;
brakeAction.canceled += OnBrakeCanceled;
}
private void OnDisable()
{
moveAction.Disable();
steerAction.Disable();
brakeAction.Disable();
moveAction.performed -= OnAccelerationPerformed;
moveAction.canceled -= OnAccelerationCanceled;
steerAction.performed -= OnSteeringPerformed;
steerAction.canceled -= OnSteeringCanceled;
brakeAction.performed -= OnBrakePerformed;
brakeAction.canceled -= OnBrakeCanceled;
}
private void OnAccelerationPerformed(InputAction.CallbackContext context)
{
float acceleration = context.ReadValue<float>();
carController.SetAcceleration(acceleration); // Replace with your method to set acceleration
}
private void OnAccelerationCanceled(InputAction.CallbackContext context)
{
carController.SetAcceleration(0); // Replace with your method to reset acceleration
}
private void OnSteeringPerformed(InputAction.CallbackContext context)
{
float steering = context.ReadValue<float>();
carController.SetSteering(steering); // Replace with your method to set steering
}
private void OnSteeringCanceled(InputAction.CallbackContext context)
{
carController.SetSteering(0); // Replace with your method to reset steering
}
private void OnBrakePerformed(InputAction.CallbackContext context)
{
carController.SetHandbrake(true); // Replace with your method to engage handbrake
}
private void OnBrakeCanceled(InputAction.CallbackContext context)
{
carController.SetHandbrake(false); // Replace with your method to release handbrake
}
// Optionally, you can implement FixedUpdate if the CarController
// expects to be updated this way. Otherwise, CarController could
// subscribe directly to Input System events for real-time updates.
private void FixedUpdate()
{
// This method can be empty if the CarController subscribes to the input actions
}
}
}
Replace SetAcceleration, SetSteering, and SetHandbrake with whatever methods you have in CarController for updating these values. This script is a fundamental guideline and may require adjustments based on the specifics of your project.
Attach this PlayerDriveController script to the player GameObject, then refer the player's CarController. Make sure a PlayerInput component is also attached to the same GameObject. Finally, assign your Input Actions Asset to the PlayerInput component, and map the action names accordingly.
If your CarController moves the car in its FixedUpdate method, you don't have to do anything in the FixedUpdate method of the PlayerDriveController. However, if your CarController expects the car's state to be set per frame (per Update method call), you would need to move the input reading there or call a method to update the car's movement based on the new state.
using System;
using UnityEngine;
using UnityEngine.InputSystem;
namespace PlayerBehaviour
{
public class PlayerDriveController : MonoBehaviour
{
public Prometeo.CarController carController;
// Reference to input actions
private PlayerInputActions inputActions;
private void Awake()
{
// Assuming CarController is on the same GameObject
carController = GetComponent<Prometeo.CarController>();
inputActions = new PlayerInputActions();
// Subscribe to the input events
inputActions.Player.Accelerate.performed += ctx => HandleAcceleration(ctx.ReadValue<float>());
inputActions.Player.Steer.performed += ctx => HandleSteering(ctx.ReadValue<float>());
inputActions.Player.Brake.performed += ctx => HandleBrake(ctx.ReadValue<float>());
inputActions.Player.Accelerate.canceled += _ => HandleAcceleration(0);
inputActions.Player.Steer.canceled += _ => HandleSteering(0);
// Assuming that Brake is a button and not an axis, a released button sends a canceled event
inputActions.Player.Brake.canceled += _ => HandleBrake(0);
}
private void OnEnable()
{
// Enable the input actions
inputActions.Player.Enable();
}
private void OnDisable()
{
// Disable the input actions
inputActions.Player.Disable();
}
private void HandleAcceleration(float value)
{
carController.CurrentAcceleration = value switch
{
> 0 => Prometeo.CarController.Acceleration.Positive,
< 0 => Prometeo.CarController.Acceleration.Negative,
_ => Prometeo.CarController.Acceleration.Neutral
};
}
private void HandleSteering(float value)
{
carController.CurrentSteering = value switch
{
> 0 => Prometeo.CarController.Steering.Right,
< 0 => Prometeo.CarController.Steering.Left,
_ => Prometeo.CarController.Steering.Straight
};
}
private void HandleBrake(float value)
{
carController.CurrentHandbrake = value > 0;
}
// Rest of your PlayerDriveController implementation...
}
// The input actions wrapper class needs to be generated by the Input Actions Asset
// If it doesn't exist, you need to create it using the Unity Editor's Input Actions window.
public class PlayerInputActions : IInputActionCollection
{
// This should be autogenerated by Unity's Input System
public class PlayerActions
{
public InputAction Accelerate;
public InputAction Steer;
public InputAction Brake;
// ... and other actions you've defined
}
public PlayerActions Player => new PlayerActions();
}
}
Also, ensure that public fields CurrentSteering, currentAcceleration, CurrentHandbrake are exposed in CarController and can receive updated values from outside.
Make sure to adjust the input action map names and action names to match what you have defined in unity. The ReadValue<float>() calls should be based on the input action configurations.
I hope this clarifies the integration and aligns with your existing CarController. Please note that Unity's Input System may require your input assets and input actions to be arranged in a specific way, so ensure that the action method names (Accelerate, Steer, Brake) match exactly to what the Input System is expecting for this code to work correctly.
using UnityEngine;
public class PlayerDriveController : MonoBehaviour
{
public Prometeo.CarController carController;
private PlayerInput playerInput; // Use the Unity Input System's PlayerInput component.
private void Awake()
{
// Assuming CarController is on the same GameObject, otherwise, you need to link it in the inspector.
carController = GetComponent<Prometeo.CarController>();
playerInput = GetComponent<PlayerInput>();
// Get actions from the input system. Replace "PlayerControls" with the name of your generated class
var actions = new PlayerControls();
// Bind actions here, replacing "Steer", "Accelerate", and "Brake" with the exact names from your input asset.
actions.Player.Steer.performed += ctx => HandleSteering(ctx.ReadValue<Vector2>());
actions.Player.Accelerate.performed += ctx => HandleAcceleration(ctx.ReadValue<float>());
actions.Player.Brake.performed += ctx => HandleBrake(ctx.ReadValue<float>());
}
private void HandleSteering(Vector2 steerValue)
{
// Your logic for handling steering using steerValue
}
private void HandleAcceleration(float accelerateValue)
{
// Your logic for handling acceleration using accelerateValue
}
private void HandleBrake(float brakeValue)
{
// Your logic for handling braking using brakeValue
}
private void OnEnable()
{
playerInput?.Enable();
}
private void OnDisable()
{
playerInput?.Disable();
}
}
In the script above, replace PlayerControls with the actual name of the class generated by the Input System. The methods HandleSteering, HandleAcceleration, and HandleBrake should contain the code for how your car controller should respond to the input values.
This script must be attached to your player's GameObject in the Inspector, and you need to ensure a PlayerInput component is present on the GameObject and is set up to reference the new input actions asset you created.
using UnityEngine;
using UnityEngine.InputSystem;
using Mirror;
namespace PlayerBehaviour
{
public class PlayerDriveController : NetworkBehaviour
{
[SerializeField] private DriveController driveController;
private YourInputActionsClassName inputActions;
private void Awake()
{
// Ensure that driveController is assigned in inspector or found via GetComponent
if (driveController == null)
driveController = GetComponent<DriveController>();
inputActions = new YourInputActionsClassName(); // Replace with the actual name generated by Unity
}
private void OnEnable()
{
if (!isLocalPlayer) return;
inputActions.Enable();
// Bind input actions to their respective handlers
inputActions.Player.Accelerate.performed += ctx => SendInput(ctx.ReadValue<float>(), inputActions.Player.Steer.ReadValue<float>(), driveController.IsNitroActive);
inputActions.Player.Accelerate.canceled += ctx => SendInput(0, inputActions.Player.Steer.ReadValue<float>(), driveController.IsNitroActive);
inputActions.Player.Steer.performed += ctx => SendInput(inputActions.Player.Accelerate.ReadValue<float>(), ctx.ReadValue<float>(), driveController.IsNitroActive);
inputActions.Player.Steer.canceled += ctx => SendInput(inputActions.Player.Accelerate.ReadValue<float>(), 0, driveController.IsNitroActive);
inputActions.Player.Brake.performed += ctx => SendBrakingInput();
inputActions.Player.Brake.canceled += ctx => SendBrakingInput();
inputActions.Player.Nitro.performed += _ => SetNitroActive(true);
inputActions.Player.Nitro.canceled += _ => SetNitroActive(false);
}
private void OnDisable()
{
inputActions.Disable();
}
private void SendInput(float acceleration, float steering, bool isNitroActive)
{
// Convert the acceleration and steering float values to the expected enums
var accelerationEnum = acceleration switch
{
> 0 => CarController.Acceleration.Positive,
< 0 => CarController.Acceleration.Negative,
_ => CarController.Acceleration.Neutral
};
var steeringEnum = steering switch
{
> 0 => CarController.Steering.Right,
< 0 => CarController.Steering.Left,
_ => CarController.Steering.Straight
};
// Send the converted input to the DriveController using your SendNewInput method
driveController.SendNewInput(accelerationEnum, steeringEnum, driveController.CurrentHandbrake);
}
private void SendBrakingInput()
{
// Send braking input to the DriveController, ensuring it is only changed when braking input has started or stopped
bool isBraking = inputActions.Player.Brake.ReadValue<float>() > 0;
driveController.SendNewInput(driveController.CurrentAcceleration, driveController.CurrentSteering, isBraking);
}
[Client]
private void SetNitroActive(bool isActive)
{
driveController.SendNitro(isActive);
}
}
}
In this script, <YourInputActionsClassName> should be replaced by the actual name of your input actions class generated by the Input Actions Asset. Also, I added a sample method for handling nitro based on how it might be triggered, given your DriveController script where you have the method SendNitro(). The SendInput method takes care of converting direct float input values into the required enum inputs that your CarController expects.
Make sure to assign the serialized driveController field through the Unity inspector or by another method in your code, and attach this script to your player GameObject. Also, ensure you've set your inputs correctly in the Input Actions Asset and that the actions names match those used in the code (Player.Accelerate, Player.Steer, Player.Brake, Player.Nitro).
Lastly, remember that you need the PlayerInput component attached to your player GameObject where this script is, and it should be hooked up to the corresponding Input Actions Asset for it to work. This PlayerDriveController script replaces your original input handling in Update and FixedUpdate and assumes that you have the proper methods or properties exposed on your DriveController to handle the inputs accordingly.
using UnityEngine;
using UnityEngine.InputSystem;
namespace PlayerBehaviour
{
public class PlayerDriveController : DriveController
{
private CarController carController;
private PlayerInput playerInput;
private InputAction accelerateAction;
private InputAction steerAction;
private InputAction brakeAction;
private InputAction nitroAction;
// We assume that the CarController component exists somewhere in the car's hierarchy
protected override void Start()
{
base.Start();
carController = CarController; // Get the CarController from the parent class
if (isLocalPlayer)
{
playerInput = GetComponent<PlayerInput>(); // Make sure PlayerInput component is attached to the GameObject
if (playerInput != null)
{
// Retrieve the actions from PlayerInput component
accelerateAction = playerInput.actions["Accelerate"];
steerAction = playerInput.actions["Steer"];
brakeAction = playerInput.actions["Brake"];
nitroAction = playerInput.actions["Nitro"];
RegisterInputActions();
}
else
{
Debug.LogError("PlayerInput component is missing on the object with PlayerDriveController.");
}
}
}
private void RegisterInputActions()
{
// Subscribe to input events
accelerateAction.performed += OnAcceleratePerformed;
accelerateAction.canceled += OnAccelerateCanceled;
steerAction.performed += OnSteerPerformed;
steerAction.canceled += OnSteerCanceled;
brakeAction.started += OnBrakeStarted;
brakeAction.canceled += OnBrakeCanceled;
nitroAction.started += OnNitroStarted;
nitroAction.canceled += OnNitroCanceled;
}
private void OnAcceleratePerformed(InputAction.CallbackContext context)
{
float accelerationValue = context.ReadValue<float>();
CurrentAcceleration = accelerationValue > 0 ? CarController.Acceleration.Positive
: accelerationValue < 0 ? CarController.Acceleration.Negative
: CarController.Acceleration.Neutral;
}
private void OnAccelerateCanceled(InputAction.CallbackContext context)
{
CurrentAcceleration = CarController.Acceleration.Neutral;
}
private void OnSteerPerformed(InputAction.CallbackContext context)
{
float steeringValue = context.ReadValue<float>();
CurrentSteering = steeringValue > 0 ? CarController.Steering.Right
: steeringValue < 0 ? CarController.Steering.Left
: CarController.Steering.Straight;
}
private void OnSteerCanceled(InputAction.CallbackContext context)
{
CurrentSteering = CarController.Steering.Straight;
}
private void OnBrakeStarted(InputAction.CallbackContext context)
{
CurrentHandbrake = true;
}
private void OnBrakeCanceled(InputAction.CallbackContext context)
{
CurrentHandbrake = false;
}
private void OnNitroStarted(InputAction.CallbackContext context)
{
SendNitro();
}
private void OnNitroCanceled(InputAction.CallbackContext context)
{
// Handle nitro cancellation if necessary
}
// Make sure to unregister events when the GameObject is disabled
private void OnDisable()
{
if (playerInput != null)
{
accelerateAction.performed -= OnAcceleratePerformed;
accelerateAction.canceled -= OnAccelerateCanceled;
steerAction.performed -= OnSteerPerformed;
steerAction.canceled -= OnSteerCanceled;
brakeAction.started -= OnBrakeStarted;
brakeAction.canceled -= OnBrakeCanceled;
nitroAction.started -= OnNitroStarted;
nitroAction.canceled -= OnNitroCanceled;
}
}
}
}
This script should replace the existing input handling code in Update or FixedUpdate within PlayerDriveController. Input actions trigger methods directly, and we use local player checks to ensure only the local player processes input. The isLocalPlayer check assumes that DriveController inherits from NetworkBehaviour and that you have defined a boolean isLocalPlayer to check if a player is local. If that is not the case, you will need to adjust the script accordingly to match your network setup.
Ensure this script is attached to your player GameObject. Be sure the PlayerInput component is present on the GameObject and is set up to reference the new input actions asset you created. Make certain that all input action names in the script ("Accelerate", "Steer", "Brake", "Nitro") match those defined in your Input Actions Asset.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem; // Needed for the new Input System
using static Prometeo.CarController;
namespace PlayerBehaviour
{
public class PlayerDriveController : DriveController
{
// Replace 'PlayerControls' with the name of the generated class from your .inputactions asset
private PlayerControls playerControls;
public PlayerDriveController() : base(Activation.LocalAndServer) { }
private void Awake()
{
// Initialize the playerControls with the actions from the Input System
playerControls = new PlayerControls();
}
private void OnEnable()
{
playerControls.Enable();
// Subscribe to the actions
playerControls.Player.Accelerate.performed += ctx => OnAccelerateInput(ctx.ReadValue<float>());
playerControls.Player.Accelerate.canceled += ctx => OnAccelerateInput(0);
playerControls.Player.Steer.performed += ctx => OnSteerInput(ctx.ReadValue<float>());
playerControls.Player.Steer.canceled += ctx => OnSteerInput(0);
playerControls.Player.Brake.performed += ctx => OnBrakeInput(ctx.ReadValue<float>() > 0);
playerControls.Player.Brake.canceled += ctx => OnBrakeInput(false);
// Optional: Handle nitro if you have it mapped in your input actions
playerControls.Player.Nitro.performed += ctx => SendNitro();
playerControls.Player.Nitro.canceled += ctx => StopNitro(); // Implement StopNitro logic if needed
}
private void OnDisable()
{
playerControls.Disable();
}
// Handle the acceleration input
private void OnAccelerateInput(float value)
{
// ... your logic for acceleration input
}
// Handle the steering input
private void OnSteerInput(float value)
{
// ... your logic for steering input
}
// Handle the brake input
private void OnBrakeInput(bool isBraking)
{
// ... your logic for brake input
}
protected override void Update()
{
base.Update();
// Your existing update logic, remove any old Input.GetKeyDown calls if they are migrated to the Input System
}
[ClientCallback]
public new void FixedUpdate()
{
// Ensure we only execute for local player in a networked environment
if (!isLocalPlayer) return;
// Your existing logic in FixedUpdate, modified to work with the new Input System
// Update the SendInput method to use the playerControls instead of Input.GetKey
}
// Use this to trigger nitro, you can call the base class method if applicable
protected void SendNitro()
{
// Your nitro logic
}
// Implement the logic to stop nitro if you need to; this may simply set a flag or call a method on CarController
protected void StopNitro()
{
// Optional: Your logic to stop nitro
}
// ... Your other methods, if any
}
}
As shown in the script, there should be an input actions wrapper class that's been generated when you created your Input Actions Asset. Replace PlayerControls with that class name in the OnEnable() and OnDisable() methods.
The OnAccelerateInput, OnSteerInput, and OnBrakeInput methods are placeholders you'll need to fill with your logic for handling the specific input changes. You'll remove any references to Unity's old Input class and replace them with the ReadValue calls to the new Input System.
This way, you keep most of the original structure, use static input actions you've defined in PlayerControls, and maintain network synchronization via DriveController. In the FixedUpdate override, you'll need to replace Input.GetKey checks with the new input system's equivalents, which might involve checking the value of actions in playerControls.
using UnityEngine;
using UnityEngine.InputSystem;
using static Prometeo.CarController;
namespace PlayerBehaviour
{
public class PlayerDriveController : DriveController
{
private PlayerControls playerControls;
private Acceleration currentAcceleration = Acceleration.Neutral;
private Steering currentSteering = Steering.Straight;
private bool currentBrake = false;
public PlayerDriveController() : base(Activation.LocalAndServer) { }
private void Awake()
{
playerControls = new PlayerControls();
playerControls.Player.Accelerate.performed += ctx => OnAccelerate(ctx.ReadValue<float>());
playerControls.Player.Steer.performed += ctx => OnSteer(ctx.ReadValue<float>());
playerControls.Player.Brake.performed += ctx => currentBrake = true;
playerControls.Player.Brake.canceled += ctx => currentBrake = false;
playerControls.Player.Nitro.performed += ctx => SendNitro();
}
private void OnEnable()
{
playerControls.Enable();
}
private void OnDisable()
{
playerControls.Disable();
}
private void OnAccelerate(float value)
{
currentAcceleration = value switch
{
> 0 => Acceleration.Positive,
< 0 => Acceleration.Negative,
_ => Acceleration.Neutral
};
UpdateInput();
}
private void OnSteer(float value)
{
currentSteering = value switch
{
> 0 => Steering.Right,
< 0 => Steering.Left,
_ => Steering.Straight
};
UpdateInput();
}
// Method to update the car's input only when there's a change
private void UpdateInput()
{
// Only send new input if there are changes
if (!isLocalPlayer) return;
SendNewInput(motor: currentAcceleration, steering: currentSteering, handbrake: currentBrake);
}
// Attempts to enable the nitro effect
protected void SendNitro()
{
if (!isLocalPlayer) return;
// Implement Nitro logic (e.g., checking cooldowns and sending RPCs)
}
// Add your FixedUpdate logic here if needed. Since we're handling input changes in the event callbacks, you may not need FixedUpdate.
[ClientCallback]
public void FixedUpdate()
{
if (!isLocalPlayer) return;
// Put here logic that needs to be updated every fixed frame, if there's any.
}
// Your remaining code...
}
}
Note the following key changes and assumptions:
I've included event callbacks for all actionable input such as steering, acceleration, braking, and nitro.
The SendNewInput method that you provided should be called whenever you want to actually update the vehicle input. I've called this inside UpdateInput which is executed whenever the input values change.
The FixedUpdate method can be left empty if all logic is handled within the input event callbacks and the Update method from DriveController. If there are other fixed frame logic to include, such as physics calculations unrelated to input, they should be included in FixedUpdate.
This script takes your structure to the new Input System, however, it assumes that the callbacks and methods for driving — such as SendNewInput and SendNitro — correctly interface with CarController and Mirror for networking.
Please customize the logic in the SendNitro method and other parts of your script to accurately reflect the logic you require. Also, ensure that the PlayerControls class name matches the one generated by the Input System based on your Input Actions Asset.
In the above code, the OnAccelerate and OnSteer methods are being called both when the input action is performed and when it's canceled. The canceled event fires when the input action stops, such as when a key is released, so you set the values back to their neutral state.
With these changes, when you release the keys (W, S, A, D), OnAccelerate(0) and OnSteer(0) will be called, resetting the acceleration to Acceleration.Neutral and the steering to Steering.Straight, respectively. The same logic applies to the braking action - when you release the brake key (Space), OnBrake(false) sets currentBrake to false.
Ensure that your PlayerControls asset has the "Continuous" interaction property set for the accelerate and steer actions; this makes sure that performed is called repeatedly while the input is active, and canceled is called once on release, as opposed to a "Press" interaction which would be suited for buttons that should respond to a single press and release cycle.
By ensuring that both positive and negative values are handled correctly in your input configuration and script logic, your car should respond correctly to forward and reverse acceleration, as well as left and right steering.
Assumptions and changes in the script:
PlayerControls is the name of the generated class based on your Input Actions Asset. Replace it with the actual name if different.
playerControls.Player.Shoot is the input action for shooting, which you need to set up in the Input Actions Asset. Replace "Player" and "Shoot" with appropriate action map and action names if they're different in your asset.
Remove the original Input.GetKey(KeyCode.Mouse0) logic since it's now being handled by the new input system.
The OnShootPerformed method acts similarly to Input.GetKey when the Shoot action is active (e.g., the mouse button is held down). The OnShootCanceled method can be used to handle when the Shoot action is released if there's a need to trigger a behavior on shoot release.
Remember to enable and disable event subscriptions in OnEnable and OnDisable to properly manage the input action lifecycle. Also, make sure to remove unnecessary Unity Input class references since they're replaced by the Input System.
In the Update method, you can use mouseDelta to get the movement from the mouse and apply it to a rotation or another mechanic in your game. Resetting mouseDelta to zero after using it ensures that you don't process the same input twice. If you're using the values in FixedUpdate instead, make sure to reset mouseDelta in FixedUpdate to match the physics update rate.
By subscribing to the performed event of the MouseX and MouseY actions, you can read the value as it changes and store it in a member variable for use in the Update method or another appropriate spot in your code.