Class PlayerInput
Represents a separate player in the game complete with a set of actions exclusive to the player and a set of paired device.
Inherited Members
Namespace: UnityEngine .InputSystem
Assembly: Unity.InputSystem.dll
Syntax
[AddComponentMenu("Input/Player Input")]
[DisallowMultipleComponent]
[HelpURL("https://docs.unity3d.com/Packages/com.unity.inputsystem@1.13/manual/PlayerInput.html")]
public class PlayerInput : MonoBehaviour
Remarks
PlayerInput is a high-level wrapper around much of the input system's functionality
which is meant to help getting set up with the new input system quickly. It takes
care of Input
The component supports local multiplayer implicitly. Each PlayerInput instance
represents a distinct user with its own set of devices and actions. To orchestrate
player management and facilitate mechanics such as joining by device activity, use
Player
The way PlayerInput notifies script code of events is determined by notification
When enabled, PlayerInput will create an Input
var p1 = PlayerInput.Instantiate(playerPrefab,
controlScheme: "KeyboardLeft", device: Keyboard.current);
var p2 = PlayerInput.Instantiate(playerPrefab,
controlScheme: "KeyboardRight", device: Keyboard.current);
If no specific devices are given to a PlayerInput, the component will look for compatible
devices present in the system and pair them to itself automatically. If the PlayerInput's
actions have control schemes defined for them, PlayerInput will look for a
control scheme for which all required devices are available and not paired to any other player.
It will try default
If no control schemes are defined, PlayerInput will try to bind as many as-of-yet unpaired devices to itself as it can match to bindings present in the actions. This means that if, for example, there's binding for both keyboard and gamepad and there is one keyboard and two gamepads available when PlayerInput is enabled, all three devices will be paired to the player.
Note that when using Player
Device pairings can be changed at any time by either manually controlling pairing through
Perform
When a player loses a device paired to it (e.g. when it is unplugged or loses power), Input
When there is only a single active PlayerInput in the game, joining is not enabled (see
joiningtrue
, device pairings for the player will also update automatically based on device usage.
If control schemes are present in actions, then if a device is used (not merely plugged in
but rather receives input on a non-noisy, non-synthetic control) which is compatible with a control scheme
other than the currently used one, PlayerInput will attempt to switch to that control scheme. Success depends
on whether all device requirements for that scheme are met from the set of available devices. If a control
scheme happens, Input
If no control schemes are present in actions, PlayerInput will automatically pair any newly available device to itself if the given device has any bindings available for it.
Both behaviors described in the previous two paragraphs are automatically disabled if more than one PlayerInput is active.
Examples
using UnityEngine;
using UnityEngine.InputSystem;
// Component to sit next to PlayerInput.
[RequireComponent(typeof(PlayerInput))]
public class MyPlayerLogic : MonoBehaviour
{
public GameObject projectilePrefab;
private Vector2 m_Look;
private Vector2 m_Move;
private bool m_Fire;
// 'Fire' input action has been triggered. For 'Fire' we want continuous
// action (that is, firing) while the fire button is held such that the action
// gets triggered repeatedly while the button is down. We can easily set this
// up by having a "Press" interaction on the button and setting it to repeat
// at fixed intervals.
public void OnFire()
{
Instantiate(projectilePrefab);
}
// 'Move' input action has been triggered.
public void OnMove(InputValue value)
{
m_Move = value.Get<Vector2>();
}
// 'Look' input action has been triggered.
public void OnLook(InputValue value)
{
m_Look = value.Get<Vector2>();
}
public void OnUpdate()
{
// Update transform from m_Move and m_Look
}
}
It is also possible to use the polling API of Input
using UnityEngine;
using UnityEngine.InputSystem;
// Component to sit next to PlayerInput.
[RequireComponent(typeof(PlayerInput))]
public class MyPlayerLogic : MonoBehaviour
{
public GameObject projectilePrefab;
private PlayerInput m_PlayerInput;
private InputAction m_LookAction;
private InputAction m_MoveAction;
private InputAction m_FireAction;
public void OnUpdate()
{
// First update we look up all the data we need.
// NOTE: We don't do this in OnEnable as PlayerInput itself performing some
// initialization work in OnEnable.
if (m_PlayerInput == null)
{
m_PlayerInput = GetComponent<PlayerInput>();
m_FireAction = m_PlayerInput.actions["fire"];
m_LookAction = m_PlayerInput.actions["look"];
m_MoveAction = m_PlayerInput.actions["move"];
}
if (m_FireAction.triggered)
/* firing logic... */;
var move = m_MoveAction.ReadValue<Vector2>();
var look = m_LookAction.ReadValue<Vector2>();
/* Update transform from move&look... */
}
}
Fields
ControlsChangedMessage
Name of the message that is sent with UnityEngine.Object.SendMessage
when the
controls used by a player are changed.
Declaration
public const string ControlsChangedMessage = "OnControlsChanged"
Field Value
Type | Description |
---|---|
string |
Remarks
The default value is on
See Also
DeviceLostMessage
Name of the message that is sent with UnityEngine.Object.SendMessage
when a
player loses a device.
Declaration
public const string DeviceLostMessage = "OnDeviceLost"
Field Value
Type | Description |
---|---|
string |
Remarks
The default value is on
See Also
DeviceRegainedMessage
Name of the message that is sent with UnityEngine.Object.SendMessage
when a
player regains a device.
Declaration
public const string DeviceRegainedMessage = "OnDeviceRegained"
Field Value
Type | Description |
---|---|
string |
Remarks
The default value is on
See Also
Properties
actionEvents
List of events invoked in response to actions being triggered.
Declaration
public ReadOnlyArray<PlayerInput.ActionEvent> actionEvents { get; set; }
Property Value
Type | Description |
---|---|
Read |
Remarks
This array is only used if notification
The list of actions will be dependent on the Input
See Also
actions
Input actions associated with the player.
Declaration
public InputActionAsset actions { get; set; }
Property Value
Type | Description |
---|---|
Input |
Asset holding the player's input actions. |
Remarks
Note that every player will maintain a unique copy of the given actions such that each player receives an identical copy. When assigning the same actions to multiple players, the first player will use the given actions as is but any subsequent player will make a copy of the actions using Instantiate.
The asset may contain an arbitrary number of action maps. By setting default
Notifications will be sent for all actions in the asset, not just for those in the first action map. This means that if additional maps are manually enabled and disabled, notifications will be sent for their actions as they receive input.
Actions can also be associated with a user via actions.
See Also
all
List of all players that are currently joined. Sorted by player
Declaration
public static ReadOnlyArray<PlayerInput> all { get; }
Property Value
Type | Description |
---|---|
Read |
List of active PlayerInputs. |
Remarks
While the list is sorted by player
See Also
camera
Optional camera associated with the player.
Declaration
public Camera camera { get; set; }
Property Value
Type | Description |
---|---|
Camera |
Remarks
Camera specific to the player or null
.
This is null
by default.
Associating a camera with a player is necessary only when using split-screen (see split
See Also
controlsChangedEvent
Event that is triggered when the controls used by the player change.
Declaration
public PlayerInput.ControlsChangedEvent controlsChangedEvent { get; }
Property Value
Type | Description |
---|---|
Player |
Remarks
This event is only used if notification
The event is trigger when the set of devices used by the player change,
when the player switches to a different control scheme (see current
See Also
currentActionMap
The currently enabled action map on the PlayerInput component.
Declaration
public InputActionMap currentActionMap { get; set; }
Property Value
Type | Description |
---|---|
Input |
Reference to the currently enabled action map or |
Remarks
Note that the concept of "current action map" is local to PlayerInput. You can still freely
enable and disable action maps directly on the actions asset. This property
only tracks which action map has been enabled under the control of PlayerInput, i.e. either
by means of default
See Also
currentControlScheme
Name of the currently active control scheme.
Declaration
public string currentControlScheme { get; }
Property Value
Type | Description |
---|---|
string | Name of the currently active control scheme or |
Remarks
Note that this property will be null
if there are no control
This can be set via Switch
See Also
defaultActionMap
Declaration
public string defaultActionMap { get; set; }
Property Value
Type | Description |
---|---|
string | Action map to enable by default or |
Remarks
By default, when enabled, PlayerInput will not enable any of the actions in the actions asset. By setting this property, however, PlayerInput can be made to automatically enable the respective action map.
It will impact the current
See Also
defaultControlScheme
The default control scheme to try to activate when the PlayerInput component is enabled
Declaration
public string defaultControlScheme { get; set; }
Property Value
Type | Description |
---|---|
string | Name of the default control scheme. |
Remarks
When PlayerInput is enabled and this is not null
and not empty, the PlayerInput
will look up the control scheme in control
Note that this property only determines the first control scheme to try. If using the control scheme fails, PlayerInput will fall back to trying the other control schemes (if any) available from actions.
Note that you can switch the current
See Also
deviceLostEvent
Event that is triggered when the player loses a device (e.g. the batteries run out).
Declaration
public PlayerInput.DeviceLostEvent deviceLostEvent { get; }
Property Value
Type | Description |
---|---|
Player |
Remarks
This event is only used if notification
See Also
deviceRegainedEvent
Event that is triggered when the player recovers from device loss and is good to go again.
Declaration
public PlayerInput.DeviceRegainedEvent deviceRegainedEvent { get; }
Property Value
Type | Description |
---|---|
Player |
Remarks
This event is only used if notification
See Also
devices
The list of devices paired to the player.
Declaration
public ReadOnlyArray<InputDevice> devices { get; }
Property Value
Type | Description |
---|---|
Read |
List of devices paired to player. |
Remarks
An InputUser also has a list of paired
See Also
hasMissingRequiredDevices
Whether the player is missed required devices. This means that the player's input setup is probably at least partially non-functional.
Declaration
public bool hasMissingRequiredDevices { get; }
Property Value
Type | Description |
---|---|
bool | True if the player is missing devices required by the control scheme. |
Remarks
This can happen, for example, if a device is unplugged during the game.
This can also be queried at user level via has
See Also
inputIsActive
Whether input is on the player is active.
Declaration
public bool inputIsActive { get; }
Property Value
Type | Description |
---|---|
bool | If true, the player is receiving input. |
Remarks
To activate and deactivate input use Activate
See Also
isSinglePlayer
Whether PlayerInput operates in single-player mode.
Declaration
public static bool isSinglePlayer { get; }
Property Value
Type | Description |
---|---|
bool | If true, there is at most a single PlayerInput. |
Remarks
Single-player mode is active while there is at most one PlayerInput (there can also be none) and
while joining is not enabled in Player
Automatic control scheme switching (if enabled) is predicated on single-player mode being active.
This is controlled by never
See Also
neverAutoSwitchControlSchemes
If true, do not automatically switch control schemes even when there is only a single player. By default, this property is false.
Declaration
public bool neverAutoSwitchControlSchemes { get; set; }
Property Value
Type | Description |
---|---|
bool | If true, do not switch control schemes when other devices are used. |
Remarks
By default, when there is only a single PlayerInput enabled (see is
When there is more than one PlayerInput or when joining is enabled Player
By setting this property to true, auto-switching of control schemes is forcibly turned off and will thus not be performed even if there is only a single PlayerInput in the game.
Note that you can still switch the current
See Also
notificationBehavior
Determines how the component notifies listeners about input actions and other input-related events pertaining to the player.
Declaration
public PlayerNotifications notificationBehavior { get; set; }
Property Value
Type | Description |
---|---|
Player |
How to trigger notifications on events. |
Remarks
By default, the component will use Send
Action Events are listed in action
See Also
playerIndex
Unique, zero-based index of the player. For example, 2
for the third player.
Declaration
public int playerIndex { get; }
Property Value
Type | Description |
---|---|
int |
Remarks
Once assigned, a player index will not change.
Note that the player index does not necessarily correspond to the player's index in all. The array will always contain all currently enabled players so when a player is disabled or destroyed, it will be removed from the array. However, the player index of the remaining players will not change.
See Also
splitScreenIndex
If split-screen is enabled (split
Declaration
public int splitScreenIndex { get; }
Property Value
Type | Description |
---|---|
int |
Remarks
Index of split-screen area assigned to player or -1 if the player is not using split-screen.
Split screen areas are enumerated row by row and within rows, column by column. So, if, for example,
there are four separate split
Split screen areas are usually assigned automatically but players can also be assigned to
areas explicitly through Instantiate(Game
See camera
See Also
uiInputModule
UI InputModule that should have it's input actions synchronized to this PlayerInput's actions.
Declaration
public InputSystemUIInputModule uiInputModule { get; set; }
Property Value
Type | Description |
---|---|
Input |
See Also
user
The internal user tied to the player.
Declaration
public InputUser user { get; }
Property Value
Type | Description |
---|---|
Input |
See Also
Methods
ActivateInput()
Enable input on the player, by enabling the current action map
Declaration
public void ActivateInput()
Remarks
Input will automatically be activated when the PlayerInput component is enabled. However, this method
can be called to reactivate input after deactivating it with Deactivate
Note that activating input will activate the current action map only (see current
Examples
PlayerInput.all[0].ActivateInput();
See Also
DeactivateInput()
Disable input on the player, by disabling the current action map
Declaration
public void DeactivateInput()
Remarks
Input is automatically activated when the PlayerInput component is enabled. This method can be used to deactivate input manually.
Note that activating input will deactivate the current action map only (see current
Examples
PlayerInput.all[0].DeactivateInput();
See Also
DebugLogAction(CallbackContext)
Debug helper method that can be hooked up to actions.
Declaration
public void DebugLogAction(InputAction.CallbackContext context)
Parameters
Type | Name | Description |
---|---|---|
Input |
context | Information about what triggered the action. |
Remarks
Debug helper method that can be hooked up to actions when using Invoke
Examples
using UnityEngine;
using UnityEngine.InputSystem;
// Component to sit next to PlayerInput.
[RequireComponent(typeof(PlayerInput))]
public class MyPlayerLogic : MonoBehaviour
{
public void OnEnable()
{
var playerInput = GetComponent<PlayerInput>();
playerInput.onActionTriggered += DebugLogAction;
}
public void OnDisable()
{
playerInput.onActionTriggered -= DebugLogAction;
}
}
See Also
FindFirstPairedToDevice(InputDevice)
Find the first PlayerInput who the given device is paired to.
Declaration
public static PlayerInput FindFirstPairedToDevice(InputDevice device)
Parameters
Type | Name | Description |
---|---|---|
Input |
device | An input device to query |
Returns
Type | Description |
---|---|
Player |
The player who is paired to the given device or |
Remarks
There could be multiple players paired to the device. This function will return the first one found.
Examples
// Find the player paired to first gamepad.
var player = PlayerInput.FindFirstPairedToDevice(Gamepad.all[0]);
Exceptions
Type | Condition |
---|---|
Argument |
|
See Also
GetDevice<TDevice>()
Return the first device of the given type from devices paired to the player.
Declaration
public TDevice GetDevice<TDevice>() where TDevice : InputDevice
Returns
Type | Description |
---|---|
TDevice | The first device paired to the player that is of the given type or |
Type Parameters
Name | Description |
---|---|
TDevice | Type of device to look for (such as Mouse). Can be a supertype of the actual device type. For example, querying for Pointer, may return a Mouse. |
Remarks
If no device of this type is paired to the player, return null
.
Examples
var device = PlayerInput.all[0].GetDevice<Mouse>();
See Also
GetPlayerByIndex(int)
Return the player with specified player index.
Declaration
public static PlayerInput GetPlayerByIndex(int playerIndex)
Parameters
Type | Name | Description |
---|---|---|
int | playerIndex | The index into the active player list. |
Returns
Type | Description |
---|---|
Player |
The player with the given player index or |
Remarks
Return the player with specified player index.
Examples
PlayerInput player = PlayerInput.GetPlayerByIndex(0);
See Also
Instantiate(GameObject, int, string, int, InputDevice)
Instantiate a player object, set up and enable its inputs.
Declaration
public static PlayerInput Instantiate(GameObject prefab, int playerIndex = -1, string controlScheme = null, int splitScreenIndex = -1, InputDevice pairWithDevice = null)
Parameters
Type | Name | Description |
---|---|---|
Game |
prefab | Prefab to clone. Must contain a PlayerInput component somewhere in its hierarchy. |
int | playerIndex | Player index to assign to the player. See player |
string | controlScheme | Control scheme to activate. |
int | splitScreenIndex | Which split screen to instantiate on. |
Input |
pairWithDevice | Device to pair to the user. By default, this is |
Returns
Type | Description |
---|---|
Player |
Newly created PlayerInput component. |
Remarks
Instantiate a player object, set up and enable its inputs.
Examples
var p1 = PlayerInput.Instantiate(playerPrefab, controlScheme: "KeyboardLeft", device: Keyboard.current);
Exceptions
Type | Condition |
---|---|
Argument |
|
See Also
Instantiate(GameObject, int, string, int, params InputDevice[])
A wrapper around Instantiate that allows instantiating a player prefab and automatically pair one or more specific devices to the newly created player.
Declaration
public static PlayerInput Instantiate(GameObject prefab, int playerIndex = -1, string controlScheme = null, int splitScreenIndex = -1, params InputDevice[] pairWithDevices)
Parameters
Type | Name | Description |
---|---|---|
Game |
prefab | A player prefab containing a Player |
int | playerIndex | Player index to instantiate. |
string | controlScheme | Control scheme to activate. |
int | splitScreenIndex | Which split screen to instantiate on. |
Input |
pairWithDevices | Which devices to limit pairing to. |
Returns
Type | Description |
---|---|
Player |
Newly created PlayerInput component. |
Remarks
Note that unlike Instantiate, this method will always activate the resulting
Game
Examples
var devices = new InputDevice[] { Gamepad.all[0], Gamepad.all[1] };
var p1 = PlayerInput.Instantiate(playerPrefab, controlScheme: "Gamepad", pairWithDevices: devices);
See Also
SwitchCurrentActionMap(string)
Switch the player to use the given action map
Declaration
public void SwitchCurrentActionMap(string mapNameOrId)
Parameters
Type | Name | Description |
---|---|---|
string | mapNameOrId | Name of the action map or its ID. |
Remarks
This method can be used to explicitly set an action map.
Examples
PlayerInput.all[0].SwitchCurrentActionMap("Player");
See Also
SwitchCurrentControlScheme(string, params InputDevice[])
Switch the player to use the given control scheme together with the given devices.
Declaration
public void SwitchCurrentControlScheme(string controlScheme, params InputDevice[] devices)
Parameters
Type | Name | Description |
---|---|---|
string | controlScheme | Name of the control scheme. See name. |
Input |
devices | A list of input devices to consider for pairing against |
Remarks
This method can be used to explicitly force a combination of control scheme and a specific set of devices. The player's currently paired devices (see devices) will get unpaired.
Examples
// Put player 1 on the "Gamepad" control scheme together
// with the second gamepad.
PlayerInput.all[0].SwitchControlScheme(
"Gamepad",
Gamepad.all[1]);
Exceptions
Type | Condition |
---|---|
Argument |
|
See Also
SwitchCurrentControlScheme(params InputDevice[])
Switch the current control scheme to one that fits the given set of devices.
Declaration
public bool SwitchCurrentControlScheme(params InputDevice[] devices)
Parameters
Type | Name | Description |
---|---|---|
Input |
devices | A list of input devices. Note that if any of the devices is already paired to another player, the device will end up paired to both players. |
Returns
Type | Description |
---|---|
bool | True if the switch was successful, false otherwise. The latter can happen, for example, if actions does not have a control scheme that fits the given set of devices. |
Remarks
The player's currently paired devices (see devices) will get unpaired.
Examples
// Switch the first player to keyboard and mouse.
PlayerInput.all[0].SwitchCurrentControlScheme(Keyboard.current, Mouse.current);
Exceptions
Type | Condition |
---|---|
Argument |
|
Invalid |
actions has not been assigned. |
See Also
Events
onActionTriggered
If notification
Declaration
public event Action<InputAction.CallbackContext> onActionTriggered
Event Type
Type | Description |
---|---|
Action<Input |
Callbacks that get called when an action triggers. |
Remarks
If notification
The callbacks are called in sync (and with the same argument) with started, performed, and canceled.
Examples
using UnityEngine;
using UnityEngine.InputSystem;
// Component to sit next to PlayerInput.
[RequireComponent(typeof(PlayerInput))]
public class MyPlayerLogic : MonoBehaviour
{
public void OnEnable()
{
var playerInput = GetComponent<PlayerInput>();
playerInput.onActionTriggered += OnAction;
}
void OnAction(InputAction.CallbackContext context)
{
}
}
See Also
onControlsChanged
If notification
Declaration
public event Action<PlayerInput> onControlsChanged
Event Type
Type | Description |
---|---|
Action<Player |
Remarks
The callback is invoked when the set of devices used by the player change,
when the player switches to a different control scheme (see current
Examples
using UnityEngine;
using UnityEngine.InputSystem;
// Component to sit next to PlayerInput.
[RequireComponent(typeof(PlayerInput))]
public class MyPlayerLogic : MonoBehaviour
{
public void OnEnable()
{
var playerInput = GetComponent<PlayerInput>();
playerInput.onControlsChanged += OnControlsChanged;
}
void OnControlsChanged(PlayerInput context)
{
}
}
See Also
onDeviceLost
If notification
Declaration
public event Action<PlayerInput> onDeviceLost
Event Type
Type | Description |
---|---|
Action<Player |
Callbacks that get called when the player loses a device. |
Remarks
If notification
The argument is the player that lost its device (i.e. the player on which the callback is installed).
Examples
using UnityEngine;
using UnityEngine.InputSystem;
// Component to sit next to PlayerInput.
[RequireComponent(typeof(PlayerInput))]
public class MyPlayerLogic : MonoBehaviour
{
public void OnEnable()
{
var playerInput = GetComponent<PlayerInput>();
playerInput.onDeviceLost += OnDeviceLost;
}
void OnDeviceLost(PlayerInput context)
{
}
}
See Also
onDeviceRegained
If notification
Declaration
public event Action<PlayerInput> onDeviceRegained
Event Type
Type | Description |
---|---|
Action<Player |
Callbacks that get called when the player regains a device. |
Remarks
If notification
The argument is the player that regained a device (i.e. the player on which the callback is installed).
Examples
using UnityEngine;
using UnityEngine.InputSystem;
// Component to sit next to PlayerInput.
[RequireComponent(typeof(PlayerInput))]
public class MyPlayerLogic : MonoBehaviour
{
public void OnEnable()
{
var playerInput = GetComponent<PlayerInput>();
playerInput.onDeviceRegained += OnDeviceRegained;
}
void OnDeviceRegained(PlayerInput player)
{
}
}