Hello everyone,
I’m trying the new input system in Unity, it’s really amazing. I’d developing a little local multiplayer game and I was wondering, how can I assign a specific input (gamepad, keyboad etc.) to the player?
I want to thank everyone in advance and sorry for my English.
Rene please could you help me?
I am triying to assing two different controllers without spawning the players with this part of your code : “p1.SwitchCurrentControlScheme(“KeyboardMouse”, Keyboard.current, Mouse.current);”. The problem came when both controllers are ps4 controllers and both players dont distinguish each controller. If I spawn the players there are not any problem, but I do not want to do this.
Thank you :).
Rene-Damm’s example is good but i think it is old.
So If you are looking for a solution without using buit-in PlayerInput component and Instantiating, my example code is below:
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Utilities;
[RequireComponent(typeof(Rigidbody))]
public class LocalPlayerController : MonoBehaviour
{
[SerializeField] private float moveSpeed = 5f;
[SerializeField] private float rotationSpeed = 720f;
[SerializeField] private PlayerInputType playerInputType = PlayerInputType.KeyboardMouse;
private ReadOnlyArray<InputDevice> keyboardMouseDevices = new ReadOnlyArray<InputDevice>(new InputDevice[] { Keyboard.current, Mouse.current });
private ReadOnlyArray<InputDevice> gamepadDevice = new ReadOnlyArray<InputDevice>(new InputDevice[] { Gamepad.current});
private Rigidbody rb;
private Vector3 movement;
private LocalPlayerInput input;
void Start()
{
rb = GetComponent<Rigidbody>();
input = new LocalPlayerInput();
input.Enable();
input.devices = playerInputType == PlayerInputType.KeyboardMouse ? keyboardMouseDevices : gamepadDevice;
input.LocalPlayer.Enable();
}
void Update()
{
Vector2 dir = input.LocalPlayer.Movement.ReadValue<Vector2>();
movement = new Vector3(dir.x, 0.0f, dir.y).normalized;
if (movement != Vector3.zero)
{
Quaternion toRotation = Quaternion.LookRotation(movement, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
}
void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
}
public enum PlayerInputType
{
KeyboardMouse,
Gamepad
}
Assign it to your player prefab and duplicate it and change Player Input Type for both of them.