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.
Namespace: UnityEngine.InputSystem
Syntax
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 InputAction bookkeeping and has a custom UI(requires the "Unity UI" package) to help setting up 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 PlayerInputManager.
The way PlayerInput notifies script code of events is determined by notificationBehavior.
By default, this is set to SendMessages which will use
// 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 InputActions (see triggered and ReadValue<TValue>()) in combination with PlayerInput.
// 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... */
}
}
When enabled, PlayerInput will create an InputUser and pair devices to the user which are then specific to the player. The set of devices can be controlled explicitly when instantiating a PlayerInput through Instantiate(GameObject, Int32, String, Int32, InputDevice[]) or Instantiate(GameObject, Int32, String, Int32, InputDevice). This also makes it possible to assign the same device to two different players, e.g. for split-keyboard play.
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 defaultControlScheme first (if set), but then fall back to trying all available schemes in order. Once a scheme is found for which all required devices are available, PlayerInput will pair those devices to itself and select the given scheme.
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 PlayerInputManager, device pairing to players is controlled from the joining logic. In that case, PlayerInput will automatically pair the device from which the player joined. If control schemes are present in actions, the first one compatible with that device is chosen. If additional devices are required, these will be paired from the pool of currently unpaired devices.
Device pairings can be changed at any time by either manually controlling pairing through PerformPairingWithDevice(InputDevice, InputUser, InputUserPairingOptions) (and related methods) using a PlayerInput's assigned user or by switching control schemes (e.g. using SwitchCurrentControlScheme(String, InputDevice[])), if any are present in the PlayerInput's actions.
When a player loses a device paired to it (e.g. when it is unplugged or loses power), InputUser will signal DeviceLost which is also surfaced as a message, deviceLostEvent, or onDeviceLost (depending on notificationBehavior). When a device is reconnected, InputUser will signal DeviceRegained which also is surfaced as a message, as deviceRegainedEvent, or onDeviceRegained (depending on notificationBehavior).
When there is only a single active PlayerInput in the game, joining is not enabled (see
joiningEnabled), and neverAutoSwitchControlSchemes is not
set to true
, 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, InputUser signals ControlSchemeChanged on onChange.
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.
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 = null
Field Value
Type | Description |
---|---|
String |
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 = null
Field Value
Type | Description |
---|---|
String |
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 = null
Field Value
Type | Description |
---|---|
String |
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 |
---|---|
ReadOnlyArray<PlayerInput.ActionEvent> |
Remarks
This array is only used if notificationBehavior is set to InvokeUnityEvents.
actions
Input actions associated with the player.
Declaration
public InputActionAsset actions { get; set; }
Property Value
Type | Description |
---|---|
InputActionAsset | 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
The asset may contain an arbitrary number of action maps. By setting defaultActionMap, one of them can be selected to enabled automatically when PlayerInput is enabled. If no default action map is selected, none of the action maps will be enabled by PlayerInput itself. Use SwitchCurrentActionMap(String) or just call Enable() directly to enable a specific map.
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.
See Also
active
Declaration
public bool active { get; }
Property Value
Type | Description |
---|---|
Boolean |
all
List of all players that are currently joined. Sorted by playerIndex in increasing order.
Declaration
public static ReadOnlyArray<PlayerInput> all { get; }
Property Value
Type | Description |
---|---|
ReadOnlyArray<PlayerInput> | List of active PlayerInputs. |
Remarks
While the list is sorted by playerIndex, note that this does not mean that the playerIndex of a player corresponds to the index in this list. If, for example, three players join and then the second player leaves, the list will contain one player with playerIndex 0 followed by one player with playerIndex 2.
See Also
camera
Optional camera associated with the player.
Declaration
public Camera camera { get; set; }
Property Value
Type | Description |
---|---|
Camera | Camera specific to the player or |
Remarks
This is null
by default.
Associating a camera with a player is necessary only when using split-screen (see splitScreen).
controlsChangedEvent
Event that is triggered when the controls used by the player change.
Declaration
public PlayerInput.ControlsChangedEvent controlsChangedEvent { get; }
Property Value
Type | Description |
---|---|
PlayerInput.ControlsChangedEvent |
Remarks
This event is only used if notificationBehavior is set to InvokeUnityEvents.
The event is trigger when the set of devices used by the player change, when the player switches to a different control scheme (see currentControlScheme), or when the bindings used by the player are changed (e.g. when rebinding them). Also, for Keyboard devices, the event is triggered when the currently used keyboard layout (see keyboardLayout) changes.
currentActionMap
The currently enabled action map.
Declaration
public InputActionMap currentActionMap { get; set; }
Property Value
Type | Description |
---|---|
InputActionMap | Reference to the currently enabled action 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 defaultActionMap or by using SwitchCurrentActionMap(String).
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 schemes
defined in actions.
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.
See Also
defaultControlScheme
The default control scheme to try.
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 controlSchemes of
actions. If found, PlayerInput will try to activate the scheme. This will
succeed only if all devices required by the control scheme are either already paired to
the player or are available as devices not used by other PlayerInputs.
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.
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 |
---|---|
PlayerInput.DeviceLostEvent |
Remarks
This event is only used if notificationBehavior is set to InvokeUnityEvents.
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 |
---|---|
PlayerInput.DeviceRegainedEvent |
Remarks
This event is only used if notificationBehavior is set to InvokeUnityEvents.
devices
The devices paired to the player.
Declaration
public ReadOnlyArray<InputDevice> devices { get; }
Property Value
Type | Description |
---|---|
ReadOnlyArray<InputDevice> | List of devices paired to player. |
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 |
---|---|
Boolean | True if the player is missing devices required by the control scheme. |
Remarks
This can happen, for example, if the a device is unplugged during the game.
See Also
inputIsActive
Whether input is on the player is active.
Declaration
public bool inputIsActive { get; }
Property Value
Type | Description |
---|---|
Boolean | If true, the player is receiving input. |
See Also
isSinglePlayer
Whether PlayerInput operates in single-player mode.
Declaration
public static bool isSinglePlayer { get; }
Property Value
Type | Description |
---|---|
Boolean | 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 PlayerInputManager (if one exists). See joiningEnabled.
Automatic control scheme switching (if enabled) is predicated on single-player mode being active.
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 |
---|---|
Boolean | If true, do not switch control schemes when other devices are used. |
Remarks
By default, when there is only a single PlayerInput enabled, we assume that the game is in single-player mode and that the player should be able to freely switch between the control schemes supported by the game. For example, if the player is currently using mouse and keyboard, but is then switching to a gamepad, PlayerInput should automatically switch to the control scheme for gamepads, if present.
When there is more than one PlayerInput or when joining is enabled PlayerInputManager, this behavior is automatically turned off as we wouldn't know which player is switching if a currently unpaired device is used.
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 control schemes manually using SwitchCurrentControlScheme(String, InputDevice[]).
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 |
---|---|
PlayerNotifications | How to trigger notifications on events. |
Remarks
By default, the component will use
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 |
---|---|
Int32 | Unique index of the player. |
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.
splitScreenIndex
If split-screen is enabled (splitScreen), this is the index of the screen area used by the player.
Declaration
public int splitScreenIndex { get; }
Property Value
Type | Description |
---|---|
Int32 | Index of split-screen area assigned to player or -1 if the player is not using split-screen. |
Remarks
Split screen areas are enumerated row by row and within rows, column by column. So, if, for example, there are four separate split-screen areas, the upper left one is #0, the upper right one is #1, the lower left one is #2, and the lower right one is #3.
Split screen areas are usually assigned automatically but players can also be assigned to areas explicitly through Instantiate(GameObject, Int32, String, Int32, InputDevice) or JoinPlayer(Int32, Int32, String, InputDevice).
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 |
---|---|
InputSystemUIInputModule |
user
The internal user tied to the player.
Declaration
public InputUser user { get; }
Property Value
Type | Description |
---|---|
InputUser |
Methods
ActivateInput()
Enable input on the player.
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 DeactivateInput().
Note that activating input will activate the current action map only (see currentActionMap).
See Also
DeactivateInput()
Disable input on the player.
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 currentActionMap).
DebugLogAction(InputAction.CallbackContext)
Debug helper method that can be hooked up to actions when using InvokeUnityEvents.
Declaration
public void DebugLogAction(InputAction.CallbackContext context)
Parameters
Type | Name | Description |
---|---|---|
InputAction.CallbackContext | context |
FindFirstPairedToDevice(InputDevice)
Find the first PlayerInput who the given device is paired to.
Declaration
public static PlayerInput FindFirstPairedToDevice(InputDevice device)
Parameters
Type | Name | Description |
---|---|---|
InputDevice | device | An input device. |
Returns
Type | Description |
---|---|
PlayerInput | The player who is paired to the given device or |
Remarks
// Find the player paired to first gamepad.
var player = PlayerInput.FindFirstPairedToDevice(Gamepad.all[0]);
GetDevice<TDevice>()
Return the first device of the given type from devices paired to the player.
If no device of this type is paired to the player, return null
.
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. |
See Also
GetPlayerByIndex(Int32)
Return the Nth player.
Declaration
public static PlayerInput GetPlayerByIndex(int playerIndex)
Parameters
Type | Name | Description |
---|---|---|
Int32 | playerIndex | Index of the player to return. |
Returns
Type | Description |
---|---|
PlayerInput | The player with the given player index or |
See Also
Instantiate(GameObject, Int32, String, Int32, InputDevice)
Instantiate a player object and set up and enable its inputs.
Declaration
public static PlayerInput Instantiate(GameObject prefab, int playerIndex = null, string controlScheme = null, int splitScreenIndex = null, InputDevice pairWithDevice = null)
Parameters
Type | Name | Description |
---|---|---|
GameObject | prefab | Prefab to clone. Must contain a PlayerInput component somewhere in its hierarchy. |
Int32 | playerIndex | Player index to assign to the player. See playerIndex. By default will be assigned automatically based on how many players are in all. |
String | controlScheme | Control scheme to activate |
Int32 | splitScreenIndex | |
InputDevice | pairWithDevice | Device to pair to the user. By default, this is |
Returns
Type | Description |
---|---|
PlayerInput |
Instantiate(GameObject, Int32, String, Int32, InputDevice[])
A wrapper around
Declaration
public static PlayerInput Instantiate(GameObject prefab, int playerIndex = null, string controlScheme = null, int splitScreenIndex = null, params InputDevice[] pairWithDevices)
Parameters
Type | Name | Description |
---|---|---|
GameObject | prefab | A player prefab containing a PlayerInput component in its hierarchy. |
Int32 | playerIndex | |
String | controlScheme | |
Int32 | splitScreenIndex | |
InputDevice[] | pairWithDevices |
Returns
Type | Description |
---|---|
PlayerInput |
Remarks
Note that unlike
PassivateInput()
Declaration
public void PassivateInput()
SwitchCurrentActionMap(String)
Declaration
public void SwitchCurrentActionMap(string mapNameOrId)
Parameters
Type | Name | Description |
---|---|---|
String | mapNameOrId |
SwitchCurrentControlScheme(String, 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. |
InputDevice[] | devices | A list of devices. |
Remarks
This method can be used to explicitly force a combination of control scheme and a specific set of devices.
// Put player 1 on the "Gamepad" control scheme together
// with the second gamepad.
PlayerInput.all[0].SwitchControlScheme(
"Gamepad",
Gamepad.all[1]);
The player's currently paired devices (see devices) will get unpaired.
See Also
SwitchCurrentControlScheme(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 |
---|---|---|
InputDevice[] | 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 |
---|---|
Boolean | 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.
// Switch the first player to keyboard and mouse.
PlayerInput.all[0]
.SwitchCurrentControlScheme(Keyboard.current, Mouse.current);
See Also
Events
onActionTriggered
If notificationBehavior is set to InvokeCSharpEvents, this event is triggered when an action fires.
Declaration
public event Action<InputAction.CallbackContext> onActionTriggered
Event Type
Type | Description |
---|---|
Action<InputAction.CallbackContext> | Callbacks that get called when an action triggers. |
Remarks
If notificationBehavior is not set to InvokeCSharpEvents, the value of this property is ignored.
The callbacks are called in sync (and with the same argument) with started, performed, and canceled.
See Also
onControlsChanged
If notificationBehavior is InvokeCSharpEvents, this event is triggered when the controls used by the players are changed.
Declaration
public event Action<PlayerInput> onControlsChanged
Event Type
Type | Description |
---|---|
Action<PlayerInput> |
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 currentControlScheme), or when the bindings used by the player are changed (e.g. when rebinding them). Also, for Keyboard devices, the callback is invoked when the currently used keyboard layout (see keyboardLayout) changes.
onDeviceLost
If notificationBehavior is InvokeCSharpEvents, this event is triggered when a device paired to the player is disconnected.
Declaration
public event Action<PlayerInput> onDeviceLost
Event Type
Type | Description |
---|---|
Action<PlayerInput> | Callbacks that get called when the player loses a device. |
Remarks
If notificationBehavior is not InvokeCSharpEvents, the value of this property is ignored.
The argument is the player that lost its device (i.e. the player on which the callback is installed).
See Also
onDeviceRegained
If notificationBehavior is InvokeCSharpEvents, this event is triggered when the player previously lost a device and has now regained it or an equivalent device.
Declaration
public event Action<PlayerInput> onDeviceRegained
Event Type
Type | Description |
---|---|
Action<PlayerInput> | Callbacks that get called when the player regains a device. |
Remarks
If notificationBehavior is not InvokeCSharpEvents, the value of this property is ignored.
The argument is the player that regained a device (i.e. the player on which the callback is installed).