Files
Fishing2/Assets/ThirdParty/Rewired/Documentation/Html/HowTos.html
2025-05-10 12:49:47 +08:00

3146 lines
273 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/BasicTemplate.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- InstanceBeginEditable name="doctitle" -->
<title>Rewired Documentation | How To's</title>
<!-- InstanceEndEditable -->
<!-- InstanceParam name="isRoot" type="boolean" value="false" -->
<!-- InstanceParam name="wide" type="boolean" value="false" -->
<link href="files/css/styles.css" rel="stylesheet" type="text/css" />
<!-- Favicons -->
<link rel="icon" type="image/x-icon" href="/projects/rewired/files/images/favicon.ico?v=1" />
<!-- Apple Icons -->
<!-- For iPad with high-resolution Retina display running iOS = 7: -->
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="files/images/favicon_152x152.png?v=1">
<!-- For iPad with high-resolution Retina display running iOS = 6: -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="files/images/favicon_144x144.png?v=1">
<!-- For iPhone with high-resolution Retina display running iOS = 7: -->
<link rel="apple-touch-icon-precomposed" sizes="120x120" href="files/images/favicon_120x120.png?v=1">
<!-- For iPhone with high-resolution Retina display running iOS = 6: -->
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="files/images/favicon_114x114.png?v=1">
<!-- For the iPad mini and the first- and second-generation iPad on iOS = 7: -->
<link rel="apple-touch-icon-precomposed" sizes="76x76" href="files/images/favicon_76x76.png?v=1">
<!-- For the iPad mini and the first- and second-generation iPad on iOS = 6: -->
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="files/images/favicon_72x72.png?v=1">
<!-- For non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
<link rel="apple-touch-icon-precomposed" href="files/images/favicon_57x57.png?v=1">
</head>
<body>
<div class="container">
<div class="google-search-bar">
<script>
(function() {
var cx = '007961148920562332911:oocvtwz5jce';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:search></gcse:search>
</div>
<div class="content">
<div class="page-body">
<div class="sidebar-nav">
<h4><a href="Documentation.html">Documentation</a></h4>
<ul>
<li><a href="Overview.html">Overview</a></li>
<li><a href="ReleaseNotes.txt">Release Notes</a></li>
</ul>
<strong>Essentials:</strong>
<ol>
<li><a href="Installation.html">Installation</a></li>
<li><a href="QuickStart.html">Quick Start</a></li>
<li><a href="BasicUsage.html">Basic Usage</a></li>
<li><a href="Deployment.html">Deployment</a></li>
<li><a href="BestPractices.html">Best Practices</a></li>
<li><a href="RewiredEditor.html">Rewired Editor</a></li>
<li><a href="http://guavaman.com/projects/rewired/docs/api-reference" target="_blank">API Reference</a></li>
</ol>
<strong>Concepts:</strong>
<ul>
<li><a href="InputManager.html">Input Manager</a></li>
<li><a href="Players.html">Players</a></li>
<li><a href="Actions.html">Actions</a></li>
<li><a href="InputBehaviors.html">Input Behaviors</a></li>
<li><a href="Controllers.html">Controllers</a></li>
<li><a href="ControllerMaps.html">Controller Maps</a></li>
<li><a href="ControllerTemplates.html">Controller Templates</a></li>
<li><a href="MapCategories.html">Map Categories</a></li>
<li><a href="Layouts.html">Layouts</a></li>
<li><a href="LayoutManager.html">Layout Manager</a></li>
<li><a href="MapEnabler.html">Map Enabler</a></li>
<li><a href="CustomControllers.html">Custom Controllers</a></li>
</ul>
<strong>Extras:</strong>
<ul>
<li><a href="ControlMapper.html" title="Control Mapper">Control Mapper</a></li>
<li><a href="Glyphs.html" title="Glyphs">Glyphs</a></li>
<li><a href="TouchControls.html" title="Touch Controls">Touch Controls</a></li>
<li><a href="UnityInputOverride.html" title="Unity Input Override">Unity Input Override</a></li>
</ul>
<strong>Misc:</strong>
<ul>
<li><a href="RewiredStandaloneInputModule.html">Rewired Standalone Input Module</a></li>
<li><a href="ComponentControls.html" title="Component Controls">Component Controls</a></li>
<li><a href="PlayerControllers.html" title="Player Controllers">Player Controllers</a></li>
<li><a href="InputMapper.html" title="Input Mapper">Input Mapper</a></li>
<li><a href="UserDataStore.html" title="User Data Store">User Data Store</a></li>
<li><a href="CustomPlatforms.html" title="User Data Store">Custom Platforms</a></li>
<li><a href="Localization.html" title="Localization">Localization</a></li>
</ul>
<strong>How To's:</strong>
<ul>
<li><a href="HowTos.html">See all topics...</a></li>
</ul>
<strong>Help:</strong>
<ul>
<li><a href="SupportedControllers.html" title="Supported Controllers">Supported Controllers</a></li>
<li><a href="Overview.html#tested-platforms" title="Tested Platforms">Tested Platforms</a></li>
<li><a href="Troubleshooting.html" title="Troubleshooting">Troubleshooting</a></li>
<li><a href="KnownIssues.html">Known Issues</a></li>
<li><a href="SpecialPlatformSupport.html" title="Special Platform Support">Special Platform Support</a></li>
<li><a href="Examples.html" title="Examples">Examples</a></li>
<li><a href="Integration.html">Integrations</a></li>
<li><a href="Updating.html" title="Updating Rewired">Updating Rewired</a></li>
</ul>
<strong>FAQ</strong>
<ul>
<li><a href="FAQ.html">See all topics...</a></li>
</ul>
<strong>Unity Help:</strong>
<ul>
<li><a href="http://docs.unity3d.com/Manual/" target="_blank">Unity Manual</a></li>
<li><a href="http://docs.unity3d.com/ScriptReference/" target="_blank">Unity Script Reference</a></li>
<li><a href="http://unity3d.com/learn/tutorials/modules" target="_blank">Unity Tutorials</a></li>
</ul>
<strong>Links:</strong>
<ul>
<li><a href="http://guavaman.com/projects/rewired">Rewired Website</a></li>
<li><a href="http://guavaman.com/projects/rewired/docs">Web Documentation</a></li>
</ul>
</div>
<div class="main-body">
<div class="logo"><a href="http://guavaman.com/projects/rewired" title="Rewired"><img src="files/images/rewired-logo.png" width="173" height="139" alt="Rewired" /></a></div>
<h1>
<!-- InstanceBeginEditable name="PageHeader" -->How To's
<!-- InstanceEndEditable -->
</h1>
<!-- InstanceBeginEditable name="MainBody" -->
<p>The following information was written under the assumption that you have already completely read and understood all documentation topics under Essentials and Concepts in the <a href="Documentation.html">Documentation</a>. If you have not done so, please do before continuing.</p>
<p><strong>Topics:</strong></p>
<ul>
<li><a href="#important-classes">Important classes</a></li>
<li><a href="#get-player">Getting a Player</a></li>
<li><a href="#get-input">Getting input</a></li>
<li><a href="#get-controller">Getting a Controller</a></li>
<li><a href="#connect-disconnect-events">Receiving Joystick connect and disconnect events</a></li>
<li><a href="#assigning-controllers">Assigning Controllers to Players</a></li>
<li><a href="#enabling-disabling-controller-maps">Enabling and disabling Controller Maps</a></li>
<li><a href="#managing-controller-maps-runtime">Managing Controller Maps at runtime</a></li>
<li><a href="#loading-controller-maps-runtime">Loading Controller Maps at runtime</a></li>
<li><a href="#get-element-name-for-action">Displaying a button/axis/key name to the user for an Action</a></li>
<li><a href="#display-glyph-for-action">Displaying a glyph for a Controller element mapped to an Action</a></li>
<li><a href="#display-glyph-for-active-elements">Displaying a glyph for the currently active Controller elements</a></li>
<li><a href="#get-mappings-for-joystick-not-attached">Getting Controller Maps for a Joystick not currently attached</a></li>
<li><a href="#get-contributing-input-sources">Getting contributing input sources for an Action</a></li>
<li><a href="#last-used-controller">Determining which Controller was last used</a></li>
<li><a href="#is-controller-gamepad">Determining if a Controller is a Gamepad</a></li>
<li><a href="#relative-absolute-axes">Handling Mouse and Joystick axes</a></li>
<li><a href="#calibrating-controller-axes">Calibrating Joystick axes</a></li>
<li><a href="#Vibration-Rumble">Vibration/Rumble</a></li>
<li><a href="#button-press-types">Handling button presses of various types</a></li>
<li><a href="#button-combos">Handling multi-button Actions</a></li>
<li><a href="#excluding-players-from-joystick-assignment">Excluding certain Players from Joystick auto-assignment</a></li>
<li><a href="#changing-configuration-settings-at-runtime">Changing configuration settings at runtime</a></li>
<li><a href="#simulating-input">Simulating Input</a></li>
<li><a href="#converting-scripts">Converting scripts from UnityEngine.Input to Rewired</a></li>
<li><a href="#exporting-constants">Exporting constants for use in scripting</a></li>
<li><a href="#actionid-property-drawer">Displaying a drop-down list of Actions in the inspector of a script</a></li>
<li><a href="#copying-input-config">Copying input configuration to another project</a></li>
<li><a href="#press-start-to-join">Implementing a &quot;Press Start to Join&quot; Joystick assignment system</a></li>
<li><a href="#saving-loading-controller-maps">Saving and loading Controller Maps</a></li>
<li><a href="#saving-loading-calibration-maps">Saving and loading Calibration Maps</a></li>
<li><a href="#modifying-input-behaviors-during-runtime">Modifying Input Behaviors during runtime</a></li>
<li><a href="#touch-controls">Creating on-screen touch controls</a></li>
<li><a href="#controller-mapping-screen">Creating a controller mapping screen</a></li>
<li><a href="#conflict-checking">Conflcit Checking</a></li>
<li><a href="#new-controller-definitions">Creating new controller definitions</a></li>
<li><a href="#new-controller-templates">Creating new controller templates</a></li>
<li><a href="#add-controller-to-existing-controller-template">Adding a controller to an existing controller template</a></li>
<li><a href="#excluding-controller-definitions">Excluding controller definitions</a></li>
<li><a href="#identifying-recognized-controllers">Identifying recognized Joysticks</a></li>
<li><a href="#identifying-joysticks-windows-fallback-or-webplayer">Identifying controllers on Windows fallback or Windows Webplayer platforms</a></li>
<li><a href="#hide-input-settings-launcher">Hiding input settings on the Unity launcher</a></li>
<li><a href="#optimization">Optimizing performance</a></li>
<li><a href="#unity-ui">Using Rewired to control Unity's new UI</a></li>
<li><a href="#appletv-siri-remote">Using Apple Siri Remote on Apple TV</a></li>
<li><a href="#using-arcadeguns-g500">Using ArcadeGuns G-500 AimTrak Light Guns</a></li>
<li><a href="#dualshock-4-special-features">Using Sony DualShock 4 special features</a></li>
<li><a href="#dualsense-special-features">Using Sony DualSense special features</a></li>
<li><a href="#nintendo-switch-controller-special-features">Using Nintendo Switch controller special features</a></li>
<li><a href="#raildriver-special-features">Using P.I. Engineering Rail Driver special features</a></li>
<li><a href="#xbox-one-controller-special-features">Using XBox One controller special features on XBox One platform</a></li>
<li><a href="#apple-game-controller-framework">Apple Game Controller Framework special features</a></li>
<li><a href="#raw-input-controller-extension">Additional Windows Raw Input controller information</a></li>
<li><a href="#direct-input-controller-extension">Additional Windows Direct Input controller information</a></li>
<li><a href="#xinput-controller-extension">Additional Windows XInput controller information</a></li>
<li><a href="#wgi-controller-extension">Additional Windows Windows Gaming Input controller information</a></li>
<li><a href="#uwp-controller-extension">Additional Universal Windows Platform (UWP) controller information</a></li>
<li><a href="#macos-controller-extension">Additional MacOS controller information</a></li>
<li><a href="#linux-controller-extension">Additional Linux controller information</a></li>
<li><a href="#enhanced-device-support-linux">Enhanced Device Support permissions on Linux</a></li>
<li><a href="#asmdef-files">Using asmdef files with Rewired</a></li>
</ul>
<p>&nbsp;</p>
<hr />
<h3><a name="important-classes" id="important-classes"></a>Important classes</h3>
<p>Rewired's API has been organized using helper classes to group methods and properties topically. This makes it easier to find the methods you are looking for through the IDE.</p>
<p><strong>Global Information:</strong></p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ReInput.htm">ReInput</a> - The main class for accessing all input-related information. </li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ReInput_PlayerHelper.htm">ReInput.players</a> - <a href="Players.html">Players</a> and Player-related information. </li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ReInput_ControllerHelper.htm">ReInput.controllers</a> - <a href="Controllers.html">Controllers</a> and controller-related information of all types.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ReInput_MappingHelper.htm">ReInput.mapping</a> - <a href="ControllerMaps.html">Controller Map</a>, <a href="Actions.html">Action</a>, <a href="InputBehaviors.html">Input Behavior</a> and other data in the <a href="RewiredEditor.html">Rewired Input Manager</a>.</li>
</ul>
<p><strong>Player-Related Information:</strong></p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Player.htm">Player</a> - Get input from the <a href="Players.html">Player</a>.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Player_ControllerHelper.htm">Player.controllers</a> - All <a href="Controllers.html">Controller</a>-related information in a <a href="Players.html">Player</a>.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Player_ControllerHelper_MapHelper.htm">Player.controllers.maps</a> - All <a href="ControllerMaps.html">Controller Map</a>-related information in a <a href="Players.html">Player</a>.</li>
</ul>
<p>&nbsp;</p>
<p>More classes are listed in the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/N_Rewired.htm">API reference</a>.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="get-player" id="get-player"></a>Getting a Player</h3>
<p>Get a <a href="Players.html">Player</a> by id or name through <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_PlayerHelper_GetPlayer.htm">ReInput.players.GetPlayer</a></p>
<p>More methods for accessing Players: <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ReInput_PlayerHelper.htm" target="_blank">ReInput.players</a></p>
<pre class="code">
using UnityEngine;
using Rewired;
public class MyClass : MonoBehaviour {
public int playerId;
private Player player;
void Awake() {
<span class="comment">// Get the Player for a particular playerId</span>
player = ReInput.players.GetPlayer(playerId);
<span class="comment">// Some more examples:</span>
<span class="comment">// Get the System Player</span>
Player systemPlayer = ReInput.players.GetSystemPlayer();
<span class="comment">// Iterating through Players (excluding the System Player)</span>
for(int i = 0; i &lt; ReInput.players.playerCount; i++) {
Player p = ReInput.players.Players[i];
}
<span class="comment">// Iterating through Players (including the System Player)</span>
for(int i = 0; i &lt; ReInput.players.allPlayerCount; i++) {
Player p = ReInput.players.AllPlayers[i];
}
}
}</pre>
<p></p>
<hr />
<h3><a name="get-input" id="get-player2"></a>Getting input</h3>
<p>There are four ways to get input in Rewired:</p>
<ol>
<li><a href="#get-input-player-polling">Polling the Player for input</a> - This is the most common method and is very similar to how you normally get input in Unity. This method uses the Player-Action system and has all the advantages that provides.</li>
<li><a href="#get-input-player-events">Using Player input events</a> - This method allows you to get input by registering for an event and receving a callback when that event takes place. This method uses the Player-Action system and has all the advantages that provides.</li>
<li><a href="#get-input-controller-polling">Polling Controllers</a> - This method ignores the Player-Action system and reads input directly from Controller Elements. This method is difficult to use and not recommended because you have to read input from axes and buttons by index.</li>
<li><a href="#get-input-controller-template-polling">Polling Controller Templates</a> - This method ignores the Player-Action system and reads input directly from Controller Template Elements. If you don't want to use the Player-Action system and you prefer programming to the Controller directly, it is recommended you use this method.</li>
</ol>
<p>&nbsp;</p>
<p><strong><a name="get-input-player-polling" id="get-input-player-polling"></a>Method 1: Player Polling</strong></p>
<p>Get input through the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Player.htm">Player</a> class.</p>
<p>Rewired mirrors Unity's method nomenclature for getting input values:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButton.htm">Player.GetButton</a> - Gets the button held state of an <a href="Actions.html">Action</a>. This will return TRUE as long as the button is held. This also applies to axes being used as buttons. </li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonDown.htm">Player.GetButtonDown</a> - Gets the button just pressed state of an <a href="Actions.html">Action</a>. This will only return TRUE only on the first frame the button is pressed or for the duration of the Button Down Buffer time limit if set in the <a href="InputBehaviors.html">Input Behavior</a> assigned to this <a href="Actions.html">Action</a>. This also applies to axes being used as buttons. </li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonUp.htm">Player.GetButtonUp</a> - Get the button just released state for an <a href="Actions.html">Action</a>. This will only return TRUE for the first frame the button is released. This also applies to axes being used as buttons.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetAxis.htm">Player.GetAxis</a> - Gets the axis value of an <a href="Actions.html">Action</a>.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Player.htm">There are many more methods available in the Player class.</a></li>
</ul>
<p>All Actions can be queried for Button or Axis value regardless of the underlying hardware mapped to that <a href="Actions.html">Action</a>.</p>
<pre class="code">
using UnityEngine;
using Rewired;
public class MyClass : MonoBehaviour {
public int playerId;
private Player player;
void Awake() {
player = ReInput.players.GetPlayer(playerId);
}
void Update() {
if(player.GetAxis(&quot;Move Horizontal&quot;) != 0.0f) {
Debug.Log(&quot;Move Horizontal!&quot;);
}
if(player.GetButtonDown(&quot;Fire&quot;)) {
Debug.Log(&quot;Fire!&quot;);
}
}
} </pre>
<p><strong><a name="get-input-player-events" id="get-input-player-events"></a>Method 2: Player Input Events</strong></p>
<p>Use delegates to receive input events from a <a href="Players.html">Player</a>. There are <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_AddInputEventDelegate.htm">numerous overloads</a> available that allow you to register to receive events on different update loops, for specific input event types, and for specific <a href="Actions.html">Actions</a>. For a list of event types and whether they require additional arguments, see <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_InputActionEventType.htm">InputActionEventType</a>.</p>
<pre class="code">
public class MyClass : MonoBehaviour {
public int playerId;
private Player player;
void Awake() {
player = ReInput.players.GetPlayer(playerId);
<span class="comment">// Add delegates to receive input events from the Player</span>
<span class="comment">// This event will be called every frame any input is updated</span>
player.AddInputEventDelegate(OnInputUpdate, UpdateLoopType.Update);
<span class="comment">// This event will be called every frame the &quot;Fire&quot; action is updated</span>
player.AddInputEventDelegate(OnFireUpdate, UpdateLoopType.Update, &quot;Fire&quot;);
<span class="comment">// This event will be called when the &quot;Fire&quot; button is first pressed</span>
player.AddInputEventDelegate(OnFireButtonDown, UpdateLoopType.Update, InputActionEventType.ButtonJustPressed, &quot;Fire&quot;);
<span class="comment">// This event will be called when the &quot;Fire&quot; button is first released</span>
player.AddInputEventDelegate(OnFireButtonUp, UpdateLoopType.Update, InputActionEventType.ButtonJustReleased, &quot;Fire&quot;);
<span class="comment"> // This event will be called every frame the &quot;Move Horizontal&quot; axis is non-zero and once more when it returns to zero.</span>
player.AddInputEventDelegate(OnMoveHorizontal, UpdateLoopType.Update, InputActionEventType.AxisActiveOrJustInactive, &quot;Move Horizontal&quot;);
<span class="comment">// This event will be called when the &quot;Jump&quot; button is held for at least 2 seconds and then released</span>
player.AddInputEventDelegate(OnJumpButtonUp, UpdateLoopType.Update, InputActionEventType.ButtonPressedForTimeJustReleased, &quot;Jump&quot;, new object[] { 2.0f });
<span class="comment">// The update loop you choose for the event matters. Make sure your chosen update loop is enabled in</span>
<span class="comment">// the Settings page of the Rewired editor or you won't receive any events.</span>
}
void OnInputUpdate(InputActionEventData data) {
switch(data.actionName) { <span class="comment">// determine which action this is</span>
case "Move Horizontal":
if(data.GetAxis() != 0.0f) Debug.Log("Move Horizontal!");
break;
case "Fire":
if(data.GetButtonDown()) Debug.Log("Fire!");
break;
}
}
void OnFireUpdate(InputActionEventData data) {
if(data.GetButtonDown()) Debug.Log("Fire!");
}
void OnFireButtonDown(InputActionEventData data) {
Debug.Log("Fire!");
}
void OnFireButtonUp(InputActionEventData data) {
Debug.Log("Fire Released!");
}
void OnJumpButtonUp(InputActionEventData data) {
Debug.Log("Jump!");
}
void OnMoveHorizontal(InputActionEventData data) {
Debug.Log(&quot;Move Horizontal: &quot; + data.GetAxis());
}
void OnDestroy() {
<span class="comment">// Unsubscribe from events when object is destroyed</span>
player.RemoveInputEventDelegate(OnInputUpdate);
player.RemoveInputEventDelegate(OnFireUpdate);
player.RemoveInputEventDelegate(OnFireButtonDown);
player.RemoveInputEventDelegate(OnFireButtonUp);
player.RemoveInputEventDelegate(OnMoveHorizontal);
player.RemoveInputEventDelegate(OnJumpButtonUp);
}
}</pre>
<p><strong><a name="get-input-controller-polling" id="get-input-controller-polling"></a>Method 3: Controller Polling</strong></p>
<p>This method gets input directly from a <a href="Controllers.html">Controller's</a> buttons and axes. This is generally not the best choice as you will lose all the advantages of the Player-centric input system including mapping. Methods for accessing element values can be found in the respective <a href="Controllers.html">Controller</a> classes:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Joystick.htm">Joystick</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Keyboard.htm">Keyboard</a></li>
<li> <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Mouse.htm">Mouse</a></li>
<li> <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_CustomController.htm">Custom Controller</a></li>
</ul>
<pre class="code">
void LogMouseValues() {
Mouse mouse = ReInput.controllers.Mouse;
Debug.Log(&quot;Left Mouse Button = &quot; + mouse.GetButton(0));
Debug.Log(&quot;Right Mouse Button (Hold) = &quot; + mouse.GetButton(1));
Debug.Log(&quot;Right Mouse Button (Down) = &quot; + mouse.GetButtonDown(1));
Debug.Log(&quot;Right Mouse Button (Up) = &quot; + mouse.GetButtonUp(1));
}
void LogPlayerJoystickValues(Player player) {
<span class="comment">// Log the button and axis values for each joystick assigned to this Player</span>
for(int i = 0; i < player.joystickCount; i++) {
Joystick joystick = player.Joysticks[i];
Debug.Log(&quot;Joystick &quot; + i + &quot;:&quot;);
LogJoystickElementValues(joystick); <span class="comment">// log all the element values in this joystick</span>
}
}
void LogJoystickElementValues(Joystick joystick) {
<span class="comment">// Log Joystick button values</span>
for(int i = 0; i &lt; joystick.buttonCount; i++) {<br /> Debug.Log(&quot;Button &quot; + i + &quot; = &quot; + joystick.Buttons[i].value); <span class="comment">// get the current value of the button</span>
}
<span class="comment">// Log Joystick axis values</span>
for(int i = 0; i &lt; joystick.axisCount; i++) {<br /> Debug.Log(&quot;Axis &quot; + i + &quot; = &quot; + joystick.Axes[i].value); <span class="comment">// get the current value of the axis</span>
}
}</pre>
<p><strong><a name="get-input-controller-template-polling" id="get-input-controller-template-polling"></a>Method 4: Controller Template Polling</strong></p>
<p>This method gets input directly from a <a href="ControllerTemplates.html">Controller Template's</a> elements. This is generally not the best choice as you will lose all the advantages of the Player-centric input system including mapping. However it does allow you to program for the controller. Methods for accessing element values can be found in the respective <a href="ControllerTemplates.html">Controller Template</a> interfaces.</p>
<p>Please see <a href="ControllerTemplates.html#getting-input-directly">Controller Templates - Getting input directly</a> for more information.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="get-controller" id="get-controller"></a>Getting a Controller</h3>
<p>You generally don't need to get <a href="Controllers.html">Controllers</a> for normal gameplay input tasks, but there are certain times when you need to get a <a href="Controllers.html">Controller</a> such as during <a href="Controllers.html">Controller</a> remapping. There are a number of ways you can get <a href="Controllers.html">Controllers</a>.</p>
<p><strong>To get a specific controller:</strong><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_ControllerHelper_GetController.htm">ReInput.controllers.GetController</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_GetController.htm">player.controllers.GetController</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_GetControllerWithTag.htm">player.controllers.GetControllerWithTag</a></p>
<p><strong>You can get the mouse from:</strong><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ReInput_ControllerHelper_Mouse.htm">ReInput.controllers.Mouse</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Player_ControllerHelper_Mouse.htm">player.controllers.Mouse</a></p>
<p><strong>You can get the keyboard from:</strong><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ReInput_ControllerHelper_Keyboard.htm">ReInput.controllers.Keyboard</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Player_ControllerHelper_Keyboard.htm">player.controllers.Keyboard </a></p>
<p><strong>You can loop through all controllers:</strong><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ReInput_ControllerHelper_Controllers.htm">ReInput.controllers.Controllers <br />
</a><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ReInput_ControllerHelper_Joysticks.htm">ReInput.controllers.Joysticks</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ReInput_ControllerHelper_CustomControllers.htm">ReInput.controllers.CustomControllers</a></p>
<p><strong>You can loop through controllers assigned to a Player:</strong><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Player_ControllerHelper_Joysticks.htm">player.controllers.Joysticks</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Player_ControllerHelper_CustomControllers.htm">player.controllers.CustomControllers</a></p>
<p>&nbsp;</p>
<hr />
<h3><a name="connect-disconnect-events" id="connect-disconnect-events"></a>Receiving Joystick connect and disconnect events</h3>
<p>To receive an event when a <a href="Controllers.html#joysticks">Joystick</a> is connected, register for <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/E_Rewired_ReInput_ControllerConnectedEvent.htm">ReInput.ControllerConnectedEvent</a>.<br />
To receive an event when a <a href="Controllers.html#joysticks">Joystick</a><a href="Controllers.html"></a> is fully disconnected, register for <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/E_Rewired_ReInput_ControllerDisconnectedEvent.htm">ReInput.ControllerDisconnectedEvent</a>.<br />
To receive an event when a <a href="Controllers.html#joysticks">Joystick</a><a href="Controllers.html"></a> is about to be disconnected, register for <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/E_Rewired_ReInput_ControllerDisconnectedEvent.htm">ReInput.ControllerPreDisconnectEvent</a>.</p>
<p>Note: <a href="Controllers.html#joysticks">Joysticks</a> are not guaranteed to be available on Awake or Start on all platforms or input sources. If <a href="Controllers.html#joysticks">Joysticks</a> are available immediately to Rewired on Awake, <a href="Controllers.html#joysticks">Joystick</a> connected events will not be sent (technically, they will, but you cannot subscribe to Rewired's events before it initializes because of Rewired's script execution order, so you can't react to these events). If <a href="Controllers.html#joysticks">Joystick</a> availability is delayed, a <a href="Controllers.html">Controller</a> connected event will be sent when Rewired detects the controller. If you need to check for the presence of <a href="Controllers.html#joysticks">Joysticks</a> at the beginning of your game, you should check in both Awake or Start and by subscribing to the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/E_Rewired_ReInput_ControllerConnectedEvent.htm">ReInput.ControllerConnectedEvent</a> or enable deferred controller connected events. The <a href="RewiredEditor.html#settings-defer-controller-connected-events-on-start">&quot;Defer Controller Connected Events On Start&quot; option in Rewired Editor -&gt; Settings</a> will defer controller connected events for controllers already connected when Rewired initializes until the Start event so that you can subscribe to the ReInput.ControllerConnectedEvent in Awake and react to the events.</p>
<pre class="code">
using UnityEngine;
using Rewired;
public MyClass : MonoBehaviour {
void Awake() {
<span class="comment">// Subscribe to events</span>
ReInput.ControllerConnectedEvent += OnControllerConnected;
ReInput.ControllerDisconnectedEvent += OnControllerDisconnected;
ReInput.ControllerPreDisconnectEvent += OnControllerPreDisconnect;
}
<span class="comment">// This function will be called when a controller is connected</span>
<span class="comment">// You can get information about the controller that was connected via the args parameter</span>
void OnControllerConnected(ControllerStatusChangedEventArgs args) {
Debug.Log(&quot;A controller was connected! Name = &quot; + args.name + &quot; Id = &quot; + args.controllerId + &quot; Type = &quot; + args.controllerType);
}
<span class="comment">// This function will be called when a controller is fully disconnected</span>
<span class="comment">// You can get information about the controller that was disconnected via the args parameter</span>
void OnControllerDisconnected(ControllerStatusChangedEventArgs args) {
Debug.Log(&quot;A controller was disconnected! Name = &quot; + args.name + &quot; Id = &quot; + args.controllerId + &quot; Type = &quot; + args.controllerType);
}
<span class="comment">// This function will be called when a controller is about to be disconnected</span>
<span class="comment">// You can get information about the controller that is being disconnected via the args parameter</span>
<span class="comment">// You can use this event to save the controller's maps before it's disconnected</span>
void OnControllerPreDisconnect(ControllerStatusChangedEventArgs args) {
Debug.Log(&quot;A controller is being disconnected! Name = &quot; + args.name + &quot; Id = &quot; + args.controllerId + &quot; Type = &quot; + args.controllerType);
}
void OnDestroy() {
<span class="comment">// Unsubscribe from events</span>
ReInput.ControllerConnectedEvent -= OnControllerConnected;
ReInput.ControllerDisconnectedEvent -= OnControllerDisconnected;
ReInput.ControllerPreDisconnectEvent -= OnControllerPreDisconnect;
}
}</pre>
<hr />
<h3><a name="assigning-controllers" id="assigning-controllers"></a><a name="assigning-joysticks" id="assigning-controllers2"></a>Assigning Controllers to Players</h3>
<p><strong>Joysticks</strong></p>
<p><a href="Controllers.html#joysticks">Joysticks</a> will be assigned to <a href="Players.html">Players</a> automatically if you have enabled and configured <a href="Controllers.html#joysticks">Joystick</a> auto-assignment in the <a href="RewiredEditor.html#Settings">Rewired Editor under Settings</a>. However, if you wish to manually assign or unassign <a href="Controllers.html#joysticks">Joysticks</a> or want to receive notifications when a controller is added/removed from a Player, you can do so with the following methods:</p>
<p><strong>Player class:</strong></p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_AddController.htm">player.controllers.AddController</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_RemoveController.htm">player.controllers.RemoveController</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_ContainsController.htm">player.controllers.ContainsController</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_ClearControllersOfType.htm">player.controllers.ClearControllersOfType</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Player_ControllerHelper_ClearAllControllers.htm">player.controllers.ClearAllControllers</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/E_Rewired_Player_ControllerHelper_ControllerAddedEvent.htm">player.controllers.ControllerAddedEvent</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/E_Rewired_Player_ControllerHelper_ControllerRemovedEvent.htm">player.controllers.ControllerRemovedEvent</a></li>
</ul>
<p><strong>ReInput class:</strong></p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_ControllerHelper_IsControllerAssigned.htm">ReInput.controllers.IsControllerAssigned</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_ReInput_ControllerHelper_IsCustomControllerAssignedToPlayer.htm">ReInput.controllers.IsControllerAssignedToPlayer</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_ControllerHelper_RemoveControllerFromAllPlayers.htm">ReInput.controllers.RemoveControllerFromAllPlayers</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_ReInput_ControllerHelper_AutoAssignJoystick.htm">ReInput.controllers.AutoAssignJoystick</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_ReInput_ControllerHelper_AutoAssignJoysticks.htm">ReInput.controllers.AutoAssignJoysticks</a> </li>
</ul>
<p>Also, see <a href="#connect-disconnect-events">Receiving joystick connect and disconnect events</a> to get a notification when a <a href="Controllers.html#joysticks">Joystick</a><a href="Controllers.html"></a> is connected or disconnected.</p>
<pre class="code">
<span class="comment">// Example: Shows how to assign Joysticks manually to the next Player that doesn't have one assigned.</span>
void Awake() {
<span class="comment">// Listen for controller connection events</span>
ReInput.ControllerConnectedEvent += OnControllerConnected;
<span class="comment">// Assign each Joystick to a Player initially</span>
foreach(Joystick j in ReInput.controllers.Joysticks) {
if(ReInput.controllers.IsJoystickAssigned(j)) continue; <span class="comment">// Joystick is already assigned</span>
<span class="comment">// Assign Joystick to first Player that doesn't have any assigned</span>
AssignJoystickToNextOpenPlayer(j);
}
}
<span class="comment">// This will be called when a controller is connected</span>
void OnControllerConnected(ControllerStatusChangedEventArgs args) {
if(args.controllerType != ControllerType.Joystick) return; <span class="comment">// skip if this isn't a Joystick</span>
<span class="comment">// Assign Joystick to first Player that doesn't have any assigned</span>
AssignJoystickToNextOpenPlayer(ReInput.controllers.GetJoystick(args.controllerId));
}
void AssignJoystickToNextOpenPlayer(Joystick j) {
foreach(Player p in ReInput.players.Players) {
if(p.controllers.joystickCount > 0) continue; <span class="comment">// player already has a joystick</span>
p.controllers.AddController(j, true); <span class="comment">// assign joystick to player</span>
return;
}
}</pre>
<p>You can also use the joystick auto-assign system to automatically assign certain Joysticks while excluding others:</p>
<pre class="code"><span class="comment">// Joystick Auto-Assignment is disabled in the Rewired Input Manager, but you can still use it to
// assign one or all Joysticks at any time.</span>
<span class="comment"></span>void OnControllerConnected(ControllerStatusChangedEventArgs args) {
if(args.controllerType != ControllerType.Joystick) return; <span class="comment">// skip if this isn't a Joystick</span>
<span class="comment">// Get the Joystick from ReInput</span>
Joystick joystick = ReInput.controllers.GetJoystick(args.controllerId);
if(joystick == null) return;
<span class="comment">// Exclude the Apple Siri Remote -- it will be left unassigned</span>
<span class="comment">// The Siri Remote's Hardware Type Guid is bc043dba-df07-4135-929c-5b4398d29579
// <a href="#identifying-recognized-controllers">See this for more information on Hardware Type GUID</a>.</span>
if(joystick.hardwareTypeGuid == new System.Guid(&quot;bc043dba-df07-4135-929c-5b4398d29579&quot;)) return;
<span class="comment">// Assign Joystick to first Player that doesn't have any assigned</span>
ReInput.controllers.AutoAssignJoystick(joystick);
}</pre>
<p><strong>Keyboard</strong></p>
<p>The Keyboard must be assigned to a Player before that Player can use it for input. However, the method of assigning the Keyboard to a Player differs from Joysticks.</p>
<p>To allow a Player access to the keyboard at the start of your game, you should check &quot;Assign Keyboard on Start&quot; in the <a href="RewiredEditor.html#Players">Rewired Editor - Players</a> page.</p>
<p>To assign the keyboard manually via scripting:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Player_ControllerHelper_hasKeyboard.htm">player.controllers.hasKeyboard</a> - Set to True to give the Player access to the keyboard.</li>
</ul>
<p><strong>Mouse</strong></p>
<p>The Mouse must be assigned to a Player before that Player can use it for input. However, the method of assigning the Mouse to a Player differs from Joysticks.</p>
<p>To allow a Player access to the mouse at the start of your game, you should check &quot;Assign Mouse on Start&quot; in the <a href="RewiredEditor.html#Players">Rewired Editor - Players</a> page.</p>
<p>To assign the mouse manually via scripting:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Player_ControllerHelper_hasMouse.htm">player.controllers.hasMouse</a> - Set to True to give the Player access to the mouse.</li>
</ul>
<p>&nbsp;</p>
<hr />
<h3><a name="enabling-disabling-controller-maps" id="enabling-disabling-controller-maps"></a>Enabling and disabling Controller Maps</h3>
<p><a href="ControllerMaps.html">Controller Maps</a> can be enabled or disabled at will via scripting. This can be useful if you want to change game modes and have a different set of controls become active. For example, opening a menu screen. Disabled <a href="ControllerMaps.html">Controller Maps</a> will not return any value when the <a href="Players.html">Player</a> is queried for an <a href="Actions.html">Action's</a> input value. <a href="ControllerMaps.html">Controller Maps</a> are stored in the <a href="https://guavaman.com/projects/rewired/docs/api-reference/?topic=html/T_Rewired_Player.htm">Player</a> class.</p>
<p>There are two approaches of working with Controller Map enabled states:</p>
<ol>
<li><strong>Direct</strong> - Individual Controller Map objects are enabled or disabled by setting the ControllerMap.enabled property or through one of the convenience methods in the Player such as <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_SetAllMapsEnabled.htm">player.controllers.maps.SetAllMapsEnabled</a>. The enabled state changes are only applied to the specific Controller Map instances at the time the state is changed. If, for example, a new Joystick is assigned to the Player, the new Joystick's Controller Maps will not automatically inherit enabled state settings from other Controller Maps. You are in complete control of how and when Controller Maps are enabled and/or disabled and must manage this depending on the specific needs of your game.</li>
<li><strong>Managed</strong> - A system is responsible for maintaining persistent Controller Map enabled states by Map Category and Layout based on user-defined settings. Controller Map enabled states can be synchronized under a variety of circumstances that could otherwise cause issues such as when assigning a new Joystick to a Player. The manager is responsible for keeping Controller Map enabled states in sync with the current settings when Controller Maps change. If you are using Controller Maps in multiple Map Categories to handle different gameplay modes such as &quot;Gameplay&quot;, &quot;UI&quot;, etc., a managed system would be beneficial. You can build your own state management system or you can use the built-in <a href="MapEnabler.html">Map Enabler</a> system.</li>
</ol>
<p><strong>Direct Method:</strong></p>
<p>The easiest way to directly enable and disable maps in a <a href="Players.html">Player</a> is to use the following methods:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_SetAllMapsEnabled.htm">player.controllers.maps.SetAllMapsEnabled</a> - Set enabled state on all maps owned by the <a href="Players.html">Player</a> or all maps for a specific <a href="Controllers.html">Controller</a> type.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_SetMapsEnabled.htm">player.controllers.maps.SetMapsEnabled</a> - Set enabled state on a group of maps owned by the <a href="Players.html">Player</a> by <a href="Controllers.html">Controller</a> type, <a href="MapCategories.html">Map Category</a>, and <a href="Layouts.html">Layout</a>.</li>
</ul>
<p>Example: Set enabled state on all of a <a href="Players.html">Player's</a> <a href="ControllerMaps.html">Controller Maps</a> in a certain <a href="MapCategories.html">Map Category</a> for all <a href="Controllers.html">Controller</a> types with one line of code.</p>
<pre class="code">
<span class="comment">// The quick way - one line of code</span>
player.controllers.maps.SetMapsEnabled(state, categoryName);</pre>
<p><strong>IMPORTANT:</strong> The above SetMapsEnabled and SetAllMapsEnabled methods are not persistent flags in Player that will set a certain category of map enabled/disabled upon loading. They are simply shortcuts for the below methods that iterate the maps currently loaded in the Player and set them enabled/disabled at the time the method is called. When new Controller Maps are loaded in the Player, either manually or when a Joystick is assigned, the newly loaded maps will be enabled/disabled based on the default enabled state settings for these maps on the Player page in the Rewired Input Manager, not based on previous calls to SetMapsEnabled. <a href="#persistent-current-controller-map-category">See this if you need to persistently set certain Map Categories enabled and others disabled</a>.</p>
<p>You can also enable and disable maps one by one by getting the maps one by one:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_GetMap.htm">player.controllers.maps.GetMap</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_GetMaps.htm">player.controllers.maps.GetMaps</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_GetAllMaps.htm">player.controllers.maps.GetAllMaps</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_GetAllMapsInCategory.htm">player.controllers.maps.GetAllMapsInCategory</a></li>
</ul>
<p>Once you have the map, enable or disable it by setting <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ControllerMap_enabled.htm">controllerMap.enabled</a> = true or <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ControllerMap_enabled.htm">controllerMap.enabled</a> = false. Disabled maps will not contribute to input.</p>
<p>Example: Set enabled state on all of a <a href="Players.html">Player's</a> <a href="ControllerMaps.html">Controller Maps</a> in a certain <a href="MapCategories.html">Map Category</a> for all <a href="Controllers.html">Controller</a> types one by one.</p>
<pre class="code">
<span class="comment">// The manual way - iterate all Controller Maps in a category and set the state manually</span>
foreach(ControllerMap map in player.controllers.maps.GetAllMapsInCategory(categoryName)) {
map.enabled = state; <span class="comment">// set the enabled state on the map</span>
} </pre>
<p><strong><a name="enabling-disabling-action-element-maps" id="enabling-disabling-action-element-maps"></a>Enabling and Disabling Action Element Maps</strong></p>
<p>Individual Action Element Maps in each Controller Map can also be enabled and disabled:</p>
<pre class="code">
<span class="comment">// Disable all individual Action Element Maps in all Controller Maps in the Player</span>
foreach(ControllerMap map in player.controllers.maps.GetAllMaps()) {
<span class="comment">// Disable all Action Element Maps of all types</span>
foreach(ActionElementMap aem in map.AllMaps) {
aem.enabled = false;
}
<span class="comment">// Disable all Button Maps (these were already disabled above but this is just for illustration)</span>
foreach(ActionElementMap aem in map.ButtonMaps) {
aem.enabled = false;
}
<span class="comment">// Try disabling all Axis Maps if this is a Joystick Map (these were also disabled above)</span>
JoystickMap joystickMap = map as JoystickMap;
if(joystickMap != null) {
foreach(ActionElementMap aem in joystickMap.AxisMaps) {
aem.enabled = false;
}
}
} </pre>
<p><strong><a name="persistent-current-controller-map-category" id="persistent-current-controller-map-category"></a>Persistent currently enabled Controller Map Category</strong></p>
<p><strong><em>Note:</em></strong><em> As of Rewired 1.1.25.0, the <a href="MapEnabler.html">Map Enabler</a> system is available in the Player to assist in persistent Controller Map enabled state management. Map Enabler is an easier solution to Controller Map enabled state managment, but may not be suitable for all use-cases. You can use the following information to build your own state managment system.</em></p>
<p>All functions to enable and disable Controller Maps act only on the Controller Maps currently existing in the Player and will not affect Controller Maps loaded after these functions are called. The Rewired Player does not contain or track a &quot;current Map Category&quot; for Controller Maps that will force certain maps to be enabled and others disabled persistently (an isssue when assigning new Controllers to a Player). Management of Controller Maps and what is and isn't loaded, enabled, or disabled at any particular time is completely up to the developer to determine. However, such functionality may be useful to maintain different control sets for different mutually-exclusive modes -- Gameplay and Menu, for example.</p>
<p>When a Joystick is assigned to a Player, Controller Maps for that Joystick will be loaded from the pre-defined defaults set up in the Rewired Input Manager if any can be found for that particular Player based on your settings on the Player page of the Rewired Editor. If you are using different Controller Maps for different game modes, the newly-loaded Controller Maps may be loaded with the wrong Controller Maps enabled for the current game mode. (For example, you change to Menu mode, then connect a Joystick.) To handle this, you must manage what Controller Maps are enabled on a Joystick not only when changing game modes, but also when a new Joystick is connected and assigned to a Player.</p>
<p>For example, when changing from Gameplay mode to Menu mode, you will need to set the state based on some variable in your script that tracks the current game mode. Controller Maps must be enabled/disabled to match the current state both at the moment you change game modes and when a new Joystick is connected (or more specifically, when a Joystick is assigned to a Player if you are manually assigning Joysticks). </p>
<p>The following is just one example of how you could handle this:</p>
<pre class="code">
public enum GameMode {
Gameplay,
Menu
}
public class PlayerControllerMapGameModeSync : MonoBehaviour {
public int playerId;
private GameMode currentGameMode; <span class="comment">// this tracks the current game mode</span>
private Player player {
get { return ReInput.isReady ? ReInput.players.GetPlayer(playerId) : null; }
}
<span class="comment">// A dictionary to look up the Map Category from the GameMode</span>
static Dictionary&lt;GameMode, string&gt; gameModeToMapCategory = new Dictionary&lt;GameMode, string&gt;() {
{ GameMode.Gameplay, "Gameplay" },
{ GameMode.Menu, "Menu" },
};
void Awake() {
<span class="comment">// Subscribe to the controller added event in Player so we can update
// Controller Maps when a new Joystick is assigned</span>
player.controllers.ControllerAddedEvent += OnControllerAdded;
}
void OnDestroy() {
player.controllers.ControllerAddedEvent -= OnControllerAdded;
}
<span class="comment">// Call this when you change game modes</span>
public void ChangeGameMode(GameMode mode) {
currentGameMode = mode; <span class="comment">// store the new game mode</span>
SetControllerMapsForCurrentGameMode(); <span class="comment">// enable the correct Controller Maps for the game mode</span>
}
<span class="comment">// This is called when a Controller is assigned to the Player</span>
void OnControllerAdded(ControllerAssignmentChangedEventArgs args) {
SetControllerMapsForCurrentGameMode();
}
<span class="comment">// Enable only the maps for the current game mode</span>
void SetControllerMapsForCurrentGameMode() {
<span class="comment">// Disable all controller maps first for all controllers of all types</span>
player.controllers.maps.SetAllMapsEnabled(false);
<span class="comment">// Enable maps for the current game mode for all controlllers of all types</span>
player.controllers.maps.SetMapsEnabled(true, gameModeToMapCategory[currentGameMode]);
}
}</pre>
<p>&nbsp;</p>
<hr />
<h3><a name="managing-controller-maps-runtime" id="enabling-disabling-controller-maps2"></a>Managing Controller Maps at runtime</h3>
<p><a href="ControllerMaps.html">Controller Maps</a> can be added, removed, cleared, and reloaded during gameplay via scripting. This can be useful if you want to load the default <a href="ControllerMaps.html">Controller Maps</a> as defined in the Rewired Editor after having made changes, or to load a <a href="ControllerMaps.html">Controller Map</a> in a different <a href="Layouts.html">Layout</a>. (Also see <a href="LayoutManager.html">Layout Manager</a> for managing Controller Maps by Layout.) <a href="ControllerMaps.html">Controller Maps</a> are stored in the <a href="https://guavaman.com/projects/rewired/docs/api-reference/?topic=html/T_Rewired_Player.htm">Player</a> class.</p>
<p>Methods:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_AddMap.htm">player.controllers.maps.AddMap</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_RemoveMap.htm">player.controllers.maps.RemoveMap</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Player_ControllerHelper_MapHelper_ClearAllMaps.htm">player.controllers.maps.ClearAllMaps</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_ClearMaps.htm">player.controllers.maps.ClearMaps</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_LoadMap.htm">player.controllers.maps.LoadMap</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Player_ControllerHelper_MapHelper_LoadDefaultMaps.htm">player.controllers.maps.LoadDefaultMaps</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Methods_T_Rewired_Player_ControllerHelper_MapHelper.htm">More methods for controller map management</a></li>
</ul>
<p>Each <a href="ControllerMaps.html">Controller Map</a> contains a list of <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ActionElementMap.htm">Action Element Maps</a>, which bind <a href="Actions.html">Actions</a> to a specific elements on a <a href="Controllers.html">Controller</a>. Each ActionElementMap represents one binding. The <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ActionElementMap.htm">various properties of the ActionElementMap</a> determine the specifics of the binding, such as the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ActionElementMap_elementType.htm">elementType</a> and <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ActionElementMap_elementIndex.htm">elementIndex</a>.</p>
<pre class="code"><span class="comment">// Iterate over all Mouse Maps assigned to this Player and log the element type and index for each ActionElementMap</span>
foreach(var controllerMap in player.controllers.maps.GetMaps(ControllerType.Mouse, 0)) {
foreach(var actionElementMap in controllerMap.AllMaps) { <span class="comment">// iterate over all maps regardless of type</span>
InputAction action = ReInput.mapping.GetAction(actionElementMap.actionId); <span class="comment">// get the Action from the binding</span>
<span class="comment">// Log the element type, element index, and the Action name</span>
Debug.Log(actionElementMap.elementType + " " + actionElementMap.elementIndex + " is bound to " + (action != null ? action.name : "nothing"));
}
}</pre>
<p>&nbsp;</p>
<hr />
<h3><a name="loading-controller-maps-runtime" id="enabling-disabling-controller-maps3"></a>Loading Controller Maps at runtime</h3>
<p>Before a <a href="Players.html">Player</a> can use a <a href="ControllerMaps.html">Controller Map</a>, it first must be loaded into that <a href="Players.html">Player</a>. <a href="ControllerMaps.html">Controller Maps</a> are loaded for each <a href="Players.html">Player</a> automatically at start (or, in the case of <a href="Controllers.html#joysticks">Joysticks</a>, they are loaded when a <a href="Controllers.html#joysticks">Joystick</a> is assigned to the <a href="Players.html">Player</a>) based on the <a href="ControllerMaps.html">Controller Map</a> assignments you've made in the <a href="RewiredEditor.html#Players">Players page of the Rewired Input Manager</a>.</p>
<p>To assign the <a href="ControllerMaps.html">Controller Map</a> at runtime via scripting or reload a default map (for example if you want to revert controls to the defaults), you would use the following methods to load a default <a href="ControllerMaps.html">Controller Map</a> from the Rewired Input Manager into a <a href="Players.html">Player</a>.</p>
<p>Methods:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_LoadMap.htm">player.controllers.maps.LoadMap</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Player_ControllerHelper_MapHelper_LoadDefaultMaps.htm">player.controllers.maps.LoadDefaultMaps</a></li>
</ul>
<p>These methods load the <a href="ControllerMaps.html">Controller Maps</a> you've created in the Rewired Input Manager into the <a href="Players.html">Player</a>. You can load <a href="ControllerMaps.html">Controller Maps</a> that have not been assigned to the <a href="Players.html">Player</a> in the Rewired Input Manager or replace existing <a href="ControllerMaps.html">Controller Maps</a> that are already assigned. Documentation about each overload can be found in the method links above.</p>
<pre class="code">
<span class="comment"></span><span class="comment">// Re-load the keyboard maps that were assigned to this Player in the Rewired Input Manager</span>
player.controllers.maps.LoadDefaultMaps(ControllerType.Keyboard);
<span class="comment">// Load joysticks maps in each joystick in the &quot;UI&quot; category and &quot;Default&quot; layout and set it to be enabled on start</span>
foreach(Joystick joystick in player.controllers.Joysticks) {
player.controllers.maps.LoadMap(ControllerType.Joystick, joystick.id, &quot;UI&quot;, &quot;Default&quot;, true);
}</pre>
<p></p>
<p>&nbsp;</p>
<hr />
<h3><a name="get-element-name-for-action" id="get-element-name-for-action"></a>Displaying a button/axis/key name to the user for an Action </h3>
<p>If you want to display some help text on the screen telling the user which button/key/axis to press for a particular <a href="Actions.html">Action</a>, you can get this information from the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ActionElementMap_elementIdentifierName.htm">ActionElementMap.elementIdenfitierName</a> property. The following example shows various ways to get this information for an <a href="Actions.html">Action</a>.</p>
<pre class="code">Player player = Rewired.ReInput.players.GetPlayer(0);
<span class="comment">// If set to true, only enabled maps will be returned</span>
bool skipDisabledMaps = true;
<span class="comment">// Get the first ActionElementMap of any type with the Action "Fire"</span>
Debug.Log(player.controllers.maps.GetFirstElementMapWithAction("Fire", skipDisabledMaps).elementIdentifierName);
<span class="comment">// Get the first button map with the Action "Jump"</span>
Debug.Log(player.controllers.maps.GetFirstButtonMapWithAction("Jump", skipDisabledMaps).elementIdentifierName);
<span class="comment">// Get the first axis map with the Action "Move Horizontal"</span>
Debug.Log(player.controllers.maps.GetFirstAxisMapWithAction("Move Horizontal", skipDisabledMaps).elementIdentifierName);
<span class="comment">// Loop over all ActionElementMaps of any type with the Action "Fire"</span>
foreach(var aem in player.controllers.maps.ElementMapsWithAction("Fire", skipDisabledMaps)) {
Debug.Log(aem.elementIdentifierName);
}
<span class="comment">// Loop over all button maps with the Action "Fire"</span>
foreach(var aem in player.controllers.maps.ButtonMapsWithAction("Fire", skipDisabledMaps)) {
Debug.Log(aem.elementIdentifierName);
}
<span class="comment">// Loop over all Axis maps with the Action "Move Horizontal"</span>
foreach(var aem in player.controllers.maps.AxisMapsWithAction("Move Horizontal", skipDisabledMaps)) {
Debug.Log(aem.elementIdentifierName);
}
<span class="comment">// All elements mapped to all joysticks in the player</span>
foreach(Joystick j in player.controllers.Joysticks) {
<span class="comment">// Loop over all Joystick Maps in the Player for this Joystick</span>
foreach(JoystickMap map in player.controllers.maps.GetMaps<JoystickMap>(j.id)) {
<span class="comment">// Loop over all button maps</span>
foreach(ActionElementMap aem in map.ButtonMaps) {
Debug.Log(aem.elementIdentifierName + " is assigned to Button " + aem.elementIndex + " with the Action " + ReInput.mapping.GetAction(aem.actionId).name);
}
<span class="comment">// Loop over all axis maps</span>
foreach(ActionElementMap aem in map.AxisMaps) {
Debug.Log(aem.elementIdentifierName + " is assigned to Axis " + aem.elementIndex + " with the Action " + ReInput.mapping.GetAction(aem.actionId).name);
}
<span class="comment">// Loop over all element maps of any type</span>
foreach(ActionElementMap aem in map.AllMaps) {
if(aem.elementType == ControllerElementType.Axis) {
Debug.Log(aem.elementIdentifierName + " is assigned to Axis " + aem.elementIndex + " with the Action " + ReInput.mapping.GetAction(aem.actionId).name);
} else if(aem.elementType == ControllerElementType.Button) {
Debug.Log(aem.elementIdentifierName + " is assigned to Button " + aem.elementIndex + " with the Action " + ReInput.mapping.GetAction(aem.actionId).name);
}
}
}
}
<span class="comment">// Log the keyboard keys assigned to an Action manually</span><br />foreach(ActionElementMap aem in player.controllers.maps.ButtonMapsWithAction(ControllerType.Keyboard, &quot;ActionName&quot;, false)) {
InputAction action = ReInput.mapping.GetAction(aem.actionId);
if(action == null) continue; <span class="comment">// invalid Action</span>
if(aem.keyCode == KeyCode.None) continue; <span class="comment">// there is no key assigned</span>
string descriptiveName = action.descriptiveName; <span class="comment">// get the descriptive name of the Action</span>
<span class="comment">// Create a string name that contains the primary key and any modifier keys</span>
string key = aem.keyCode.ToString(); <span class="comment">// get the primary key code as a string</span>
if(aem.modifierKey1 != ModifierKey.None) key += &quot; + &quot; + aem.modifierKey1.ToString();
if(aem.modifierKey2 != ModifierKey.None) key += &quot; + &quot; + aem.modifierKey2.ToString();
if(aem.modifierKey3 != ModifierKey.None) key += &quot; + &quot; + aem.modifierKey3.ToString();
<span class="comment">// Treat axis-type Actions differently than button-type Actions because axis contribution could be positive or negative
// It's generally safe to assume positive contribution for button-type Actions</span>
if(action.type == InputActionType.Axis) { <span class="comment">// this is an axis-type Action</span>
<span class="comment">// Determine if it contributes to the positive or negative value of the Action</span>
if(aem.axisContribution == Pole.Positive) { <span class="comment">// positive</span>
descriptiveName = !string.IsNullOrEmpty(action.positiveDescriptiveName) ?
action.positiveDescriptiveName : <span class="comment">// use the positive name if one exists</span>
action.descriptiveName + &quot; +&quot;; <span class="comment">// use the descriptive name with sign appended if not</span>
} else { <span class="comment">// negative</span>
descriptiveName = !string.IsNullOrEmpty(action.negativeDescriptiveName) ?
action.negativeDescriptiveName : <span class="comment">// use the negative name if one exists</span>
action.descriptiveName + &quot; -&quot;; <span class="comment">// use the descriptive name with sign appended if not</span>
}
}
Debug.Log(descriptiveName + &quot; is assigned to &quot; + key);
} </pre>
<p>You can also display the <a href="ControllerTemplates.html">Controller Template</a> element name for an Action:</p>
<pre class="code">
<span class="comment">// Get the Controller Template</span>
var gamepad = controller.GetTemplate&lt;IGamepadTemplate&gt;();
if(gamepad == null) return;
<span class="comment">// Get the first button map with the Action &quot;Jump&quot;</span>
var mapping = player.controllers.maps.GetFirstElementMapWithAction("Jump", skipDisabledMaps);
if(mapping == null) return;
<span class="comment">// Get the Controller Template Element Targets for the Action Element Map</span>
int targetCount = gamepad.GetElementTargets(mapping, results);
for(int i = 0; i &lt; targetCount; i++) {
Debug.Log(results[i].descriptiveName);
}</pre>
<p>&nbsp;</p>
<hr />
<h3><a name="display-glyph-for-action" id="display-glyph-for-action"></a>Displaying a glyph for a Controller element mapped to an Action </h3>
<p><strong>As of Rewired 1.1.56.0, displaying glyphs can be more easily handled by using the built-in glyph system. <a href="Glyphs.html">See this for more information</a>.</strong> Specifically, <a href="Glyphs.html#unity-ui-player-controller-element-glyph">this component can display the glyph(s) for controller elements mapped to an Action for a Player</a>.</p>
<p>The following information is considered outdated, but remains for reference.</p>
<p>&nbsp;</p>
<hr style="width: 50%; margin: 0 auto;"/>
<p>&nbsp;</p>
<ul>
<li><a href="#display-glyph-for-action-joystick">Joysticks</a></li>
<li><a href="#display-glyph-for-action-keyboard">Keyboard</a></li>
<li><a href="#display-glyph-for-action-mouse">Mouse</a></li>
</ul>
<p><strong><a name="display-glyph-for-action-joystick" id="display-glyph-for-action-joystick"></a>Joysticks:</strong></p>
<p>There are two different types of glyphs you can display for a Joystick:</p>
<ol>
<li><a href="#display-glyph-for-action-controller-specific">Glyphs based on the Controller elements specific to that Controller (recommended).</a></li>
<li><a href="#display-glyph-for-action-template-specific">Glyphs based on Controller Template elements.</a></li>
</ol>
<p>Normally, you would want to show glyphs based on the specific controller elements such as &quot;X&quot; on an Xbox controller, &quot;Cross&quot; on a Dual Shock 4, etc. If that's what you want to show, use <a href="#display-glyph-for-action-controller-specific">method 1</a>.</p>
<p>If instead you want to show generic glyphs based on a Controller Template such as the Gamepad Template (Action Bottom Row 1, Center 1, etc.), use <a href="#display-glyph-for-action-template-specific">method 2</a>.</p>
<p><strong><a name="display-glyph-for-action-controller-specific" id="display-glyph-for-action-controller-specific"></a>Method 1 - Displaying glyphs for elements on specific Joysticks:</strong></p>
<p>There are three steps involved in displaying on-screen glyphs for <a href="Controllers.html#joysticks">Joystick</a> elements:</p>
<ol>
<li>Create the <a href="Controllers.html#joysticks">Joystick</a><a href="Controllers.html"></a> element glyph graphics.</li>
<li>Create a lookup table of <a href="Controllers.html#joysticks">Joystick</a><a href="Controllers.html"></a> element glyphs.</li>
<li>Display the glyph on-screen.</li>
</ol>
<p>Step 1:<br />
Obviously this is up to you to decide how your glyphs will look and in what data format they will be in.</p>
<p>Step 2:<br />
You will need to create a lookup table that associates particular Element Identifiers from particular <a href="Controllers.html#joysticks">Joysticks</a> to the glyphs. This could be in any format you choose -- a database lookup, serialized data in a MonoBehaviour, etc.</p>
<p>(To save time, you can <a href="https://guavaman.com/rewired/files/docs/RewiredControllerElementIdentifiersCSV.zip">download a CSV file of the current controller element identifiers here</a>.)<br />
(You can <a href="https://guavaman.com/rewired/files/docs/RewiredControllersCSV.zip">download a CSV file of the current Controllers here</a>.)</p>
<p>This would look something like this in concept:</p>
<table width="100%" border="0">
<tr>
<td><strong>Joystick</strong></td>
<td><strong>Guid</strong></td>
<td><strong>Element Identifier</strong></td>
<td><strong>Glyph</strong></td>
</tr>
<tr>
<td>Xbox 360 Controller</td>
<td>d74a350e-fe8b-4e9e-bbcd-efff16d34115</td>
<td>0</td>
<td>360_LeftStick_Horiz</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>1</td>
<td>360_LeftStick_Vert</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>6</td>
<td>360_ButtonA</td>
</tr>
</table>
<p>&nbsp;</p>
<p>The most important Joysticks to support are:</p>
<ul>
<li>Unknown Controller (used for all unrecognized controllers)</li>
<li>Xbox 360 Controller (used for all XInput-compatible gamepads on Windows when Use XInput is enabled)</li>
<li>Xbox One Controller</li>
<li>Sony DualShock 4</li>
<li>Sony DualSense</li>
<li>Nintendo Pro Controller</li>
<li>Steam Controller (used for the Steam Controller on Windows Gaming Input, OSX, Linux)</li>
<li>iOS MFi Gamepad (used for all gamepads on iOS and tvOS)</li>
<li>Standardized Gamepad (used for unrecognized gamepads on Android)</li>
</ul>
<p>Step 3:<br />
Display the glyph on screen. This is up to you however you choose to do so depending on your data format and needs.</p>
<p>You can retrieve the glpyh based on the <a href="Controllers.html#joysticks">Joystick's</a> GUID and the current Element Identifier Id mapped to a particular <a href="Actions.html">Action</a>.</p>
<p>Here are the basic steps:</p>
<ol>
<li>Get the last used <a href="Controllers.html">Controller</a> from the <a href="Players.html">Player</a> using <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_ControllerHelper_GetLastActiveController.htm">Player.controllers.GetLastActiveController</a>.</li>
<li>Determine the type of the <a href="Controllers.html">Controller</a> using the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Controller_type.htm">Controller.type</a> property.</li>
<li>If a <a href="Controllers.html#joysticks">Joystick</a>, identify this <a href="Controllers.html#joysticks">Joystick</a> as a recognized type using the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Controller_hardwareTypeGuid.htm">Joystick.hardwareTypeGuid</a> property. (The type GUID for each recognized <a href="Controllers.html">Controller</a> can be found <a href="https://guavaman.com/rewired/files/docs/RewiredControllersCSV.zip">in this CSV file</a>.)</li>
<li>Check if any element on this <a href="Controllers.html">Controller</a> is mapped to the <a href="Actions.html">Action</a> in question using one of the following methods:
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_GetFirstElementMapWithAction.htm">Player.controllers.maps.GetFirstElementMapWithAction</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_GetFirstButtonMapWithAction.htm">Player.controllers.maps.GetFirstButtonMapWithAction</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_GetFirstAxisMapWithAction.htm">Player.controllers.maps.GetFirstAxisMapWithAction</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_ElementMapsWithAction.htm">Player.controllers.maps.ElementMapsWithAction</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_ButtonMapsWithAction.htm">Player.controllers.maps.ButtonMapsWithAction</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_AxisMapsWithAction.htm">Player.controllers.maps.AxisMapsWithAction</a></li>
</ul>
</li>
<li>If the element is mapped, use this information to look up the glyph from your lookup table using the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ActionElementMap.htm">ActionElementMap.elementIdentifierId</a> property and the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Controller_hardwareTypeGuid.htm">Joystick.hardwareTypeGuid</a> property.</li>
<li>Optional: Further information about the mapping can be found in the ActionElementMap such as the Axis Range, Axis Contribution, type, or other useful information should you need more specific glyphs for a finer level of detail.</li>
</ol>
<p>Below is a basic example that shows both one method of storing the glyph lookup data and how to get the current element glyph for an <a href="Actions.html">Action</a>.</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/files/docs/ShowControllerGlyphsExample.zip">A more complete example that shows handling Joystick, Keyboard (including modifier keys), and Mouse glyphs can be downloaded here.</a></li>
</ul>
<pre class="code">
<span class="comment">// ShowControllerGlyphs.cs</span>
using UnityEngine;
using System.Collections;
namespace Rewired.Demos {
<span class="comment"> // Shows how to display a glyph for an Action based on the current controller the player is using</span>
public class ShowControllerGlyphs : MonoBehaviour {
public string showGlyphHelpForAction;
<span class="comment">// Using OnGUI for Unity 4.3 compatibility
// You would probably want to use Unity UI in 4.6+ instead</span>
void OnGUI() {
ShowGlyphs();
}
void ShowGlyphs() {
<span class="comment">// Get the Rewired Player</span>
Player p = ReInput.players.GetPlayer(0); // just use Player 0 in this example
<span class="comment">// Get the last active controller the Player was using</span>
Controller activeController = p.controllers.GetLastActiveController();
if(activeController == null) { <span class="comment">// player hasn't used any controllers yet</span>
// No active controller, set a default
if(p.controllers.joystickCount > 0) { <span class="comment">// try to get the first joystick in player</span>
activeController = p.controllers.Joysticks[0];
} else { <span class="comment">// no joysticks assigned, just get keyboard</span>
activeController = p.controllers.Keyboard;
}
}
<span class="comment">// Display glyph help for a fixed Action - UI Help example</span>
if(!string.IsNullOrEmpty(showGlyphHelpForAction)) {
InputAction action = ReInput.mapping.GetAction(showGlyphHelpForAction); <span class="comment">// get the Action for the current string</span>
if(action != null) { <span class="comment">// make sure this is a valid action</span>
ShowGlyphHelp(p, activeController, action);
}
}
}
void ShowGlyphHelp(Player p, Controller controller, InputAction action) {
if(p == null || controller == null || action == null) return;
<span class="comment">// Find the first element mapped to this Action on this controller</span>
ActionElementMap aem = p.controllers.maps.GetFirstElementMapWithAction(controller, action.id, true);
if(aem == null) return; <span class="comment">// nothing was mapped on this controller for this Action</span>
if(controller.type != ControllerType.Joystick) return; <span class="comment">// this example only supports joystick glyphs</span>
<span class="comment">// Find the glyph for the element on the controller</span>
Sprite glyph = ControllerGlyphs.GetGlyph((controller as Joystick).hardwareTypeGuid, aem.elementIdentifierId, aem.axisRange);
if(glyph == null) return; <span class="comment">// no glyph found</span>
<span class="comment">// Draw the glyph to the screen</span>
Rect rect = new Rect(0, 30, glyph.textureRect.width, glyph.textureRect.height);
GUI.Label(new Rect(rect.x, rect.y + rect.height + 20, rect.width, rect.height), action.descriptiveName);
GUI.DrawTexture(rect, glyph.texture);
}
}
}</pre>
<pre class="code">
<span class="comment">// ControllerGlpyhs.cs</span>
using UnityEngine;
using System.Collections;
namespace Rewired.Demos {
using Rewired.Data.Mapping;
<span class="comment"> // This is a basic example showing one way of storing glyph data for Joysticks</span>
public class ControllerGlyphs : MonoBehaviour {
[SerializeField]
private ControllerEntry[] controllers;
private static ControllerGlyphs Instance;
void Awake() {
Instance = this; <span class="comment">// set up a singleton</span>
}
public static Sprite GetGlyph(System.Guid joystickGuid, int elementIdentifierId, AxisRange axisRange) {
if(Instance == null) return null;
if(Instance.controllers == null) return null;
<span class="comment">// Try to find the glyph</span>
for(int i = 0; i < Instance.controllers.Length; i++) {
if(Instance.controllers[i] == null) continue;
if(Instance.controllers[i].joystick == null) continue; // no joystick assigned
if(Instance.controllers[i].joystick.Guid != joystickGuid) continue; // guid does not match
return Instance.controllers[i].GetGlyph(elementIdentifierId, axisRange);
}
return null;
}
[System.Serializable]
private class ControllerEntry {
public string name;
<span class="comment"> // This must be linked to the HardwareJoystickMap located in Rewired/Internal/Data/Controllers/HardwareMaps/Joysticks</span>
public HardwareJoystickMap joystick;
public GlyphEntry[] glyphs;
public Sprite GetGlyph(int elementIdentifierId, AxisRange axisRange) {
if(glyphs == null) return null;
for(int i = 0; i < glyphs.Length; i++) {
if(glyphs[i] == null) continue;
if(glyphs[i].elementIdentifierId != elementIdentifierId) continue;
return glyphs[i].GetGlyph(axisRange);
}
return null;
}
}
[System.Serializable]
private class GlyphEntry {
public int elementIdentifierId;
public Sprite glyph;
public Sprite glyphPos;
public Sprite glyphNeg;
public Sprite GetGlyph(AxisRange axisRange) {
switch(axisRange) {
case AxisRange.Full: return glyph;
case AxisRange.Positive: return glyphPos != null ? glyphPos : glyph;
case AxisRange.Negative: return glyphNeg != null ? glyphNeg : glyph;
}
return null;
}
}
}
}</pre>
<p><strong><a name="display-glyph-for-action-template-specific" id="display-glyph-for-action-template-specific"></a>Method 2 - Displaying glyphs for elements on Controller Templates:</strong></p>
<p>Only <a href="SupportedControllers.html">recognized Controllers listed here</a> are compatible with <a href="ControllerTemplates.html">Controller Templates</a>. Unknown Controllers cannot use Controller Templates and will not be able to use this system.</p>
<p>There are three steps involved in displaying on-screen glyphs for <a href="ControllerTemplates.html">Controller Template</a> elements:</p>
<ol>
<li>Create the <a href="ControllerTemplates.html">Controller Template</a><a href="Controllers.html#joysticks"></a><a href="Controllers.html"></a> element glyph graphics.</li>
<li>Create a lookup table of <a href="ControllerTemplates.html">Controller Template</a><a href="Controllers.html#joysticks"></a><a href="Controllers.html"></a> element glyphs.</li>
<li>Display the glyph on-screen.</li>
</ol>
<p>Step 1:<br />
Obviously this is up to you to decide how your glyphs will look and in what data format they will be in.</p>
<p>Step 2:<br />
You will need to create a lookup table that associates particular Element Identifiers from particular <a href="ControllerTemplates.html">Controller Templates</a><a href="Controllers.html#joysticks"></a> to the glyphs. This could be in any format you choose -- a database lookup, serialized data in a MonoBehaviour, etc.</p>
<p>(To save time, you can <a href="https://guavaman.com/rewired/files/docs/RewiredControllerTemplateElementIdentifiersCSV.zip">download a CSV file of the current Controller Template element identifiers here</a>.)<br />
(You can also <a href="https://guavaman.com/rewired/files/docs/RewiredControllerTemplatesCSV.zip">download a CSV file of the current Controller Templates here</a>.)</p>
<p>This would look something like this in concept:</p>
<table width="100%" border="0">
<tr>
<td><strong>Controller Template</strong></td>
<td><strong>Guid</strong></td>
<td><strong>Element Identifier</strong></td>
<td><strong>Glyph</strong></td>
</tr>
<tr>
<td>Gamepad Template</td>
<td>83b427e4-086f-47f3-bb06-be266abd1ca5</td>
<td>0</td>
<td>LeftStick_Horiz</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>1</td>
<td>LeftStick_Vert</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>4</td>
<td>ButtonA</td>
</tr>
</table>
<p>&nbsp;</p>
<p>The most important Controller Template to support is the Gamepad Template.</p>
<p>Step 3:<br />
Display the glyph on screen. This is up to you however you choose to do so depending on your data format and needs.</p>
<p>You can retrieve the glpyh based on the <a href="ControllerTemplates.html">Controller Template's</a> GUID and the current Element Identifier Id mapped to a particular <a href="Actions.html">Action</a>.</p>
<p>Here are the basic steps:</p>
<ol>
<li>Get the last used <a href="Controllers.html">Controller</a> from the <a href="Players.html">Player</a> using <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_ControllerHelper_GetLastActiveController.htm">Player.controllers.GetLastActiveController</a>.</li>
<li>Get the first <a href="ControllerTemplates.html">Controller Template</a> from the Controller using the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Controller_Templates.htm">Controller.Templates</a> property.</li>
<li>Use the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_IControllerTemplate_typeGuid.htm">IControllerTemplate.typeGuid</a> property to look up the glyph. (The type GUID for each <a href="ControllerTemplates.html">Controller Template</a> can be found in <a href="https://guavaman.com/rewired/files/docs/RewiredControllerTemplatesCSV.zip">this CSV file</a>.)</li>
<li>Check if any element on this <a href="Controllers.html">Controller</a><a href="ControllerTemplates.html"></a><a href="Controllers.html"></a> is mapped to the <a href="Actions.html">Action</a> in question using one of the following methods:
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_GetFirstElementMapWithAction.htm">Player.controllers.maps.GetFirstElementMapWithAction</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_GetFirstButtonMapWithAction.htm">Player.controllers.maps.GetFirstButtonMapWithAction</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_GetFirstAxisMapWithAction.htm">Player.controllers.maps.GetFirstAxisMapWithAction</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_ElementMapsWithAction.htm">Player.controllers.maps.ElementMapsWithAction</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_ButtonMapsWithAction.htm">Player.controllers.maps.ButtonMapsWithAction</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_AxisMapsWithAction.htm">Player.controllers.maps.AxisMapsWithAction</a></li>
</ul>
</li>
<li><a href="ControllerTemplates.html#action-map-to-controller-template-element">Convert the returned Action Element Map into a Controller Template Element Target</a> by passing the Action Element Map to the IControllerTemplate.GetElementTargets method.</li>
<li>Use this information to look up the glyph from your lookup table using the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_IControllerTemplateElement_id.htm">ControllerTemplateElementTarget.element.id</a> property and the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_IControllerTemplate_typeGuid.htm">IControllerTemplate.typeGuid</a> property.</li>
<li>Optional: Further information about the mapping can be found in the ControllerTemplateElementTarget such as the Axis Range or other useful information should you need more specific glyphs for a finer level of detail.</li>
</ol>
<p>Below is a basic example that shows both one method of storing the glyph lookup data and how to get the current element glyph for an <a href="Actions.html">Action</a>.</p>
<pre class="code"><span class="comment">// ShowControllerTemplateGlyphs.cs</span>
using UnityEngine;
using System.Collections.Generic;
namespace Rewired.Demos {
<span class="comment">// Shows how to display a glyph for an Action based on the current controller the player is using</span>
public class ShowControllerTemplateGlyphs : MonoBehaviour {
public string showGlyphHelpForAction;
<span class="comment">// A temporary working list to use</span>
private List<ControllerTemplateElementTarget> _tempTemplateElementTargets = new List<ControllerTemplateElementTarget>();
<span class="comment">// Using OnGUI for Unity 4.3 compatibility
// You would probably want to use Unity UI in 4.6+ instead</span>
void OnGUI() {
ShowGlyphs();
}
void ShowGlyphs() {
<span class="comment">// Get the Rewired Player</span>
Player p = ReInput.players.GetPlayer(0); // just use Player 0 in this example
<span class="comment">// Get the last active controller the Player was using</span>
Controller activeController = p.controllers.GetLastActiveController();
if(activeController == null) { // player hasn't used any controllers yet
<span class="comment">// No active controller, set a default</span>
if(p.controllers.joystickCount > 0) { <span class="comment">// try to get the first joystick in player</span>
activeController = p.controllers.Joysticks[0];
} else { <span class="comment">// no joysticks assigned, just get keyboard</span>
activeController = p.controllers.Keyboard;
}
}
<span class="comment">// Display glyph help for a fixed Action - UI Help example</span>
if(!string.IsNullOrEmpty(showGlyphHelpForAction)) {
InputAction action = ReInput.mapping.GetAction(showGlyphHelpForAction); <span class="comment">// get the Action for the current string</span>
if(action != null) { <span class="comment">// make sure this is a valid action</span>
ShowGlyphHelp(p, activeController, action);
}
}
}
void ShowGlyphHelp(Player p, Controller controller, InputAction action) {
if(p == null || controller == null || action == null) return;
<span class="comment">// Find the first element mapped to this Action on this controller</span>
ActionElementMap aem = p.controllers.maps.GetFirstElementMapWithAction(controller, action.id, true);
if(aem == null) return; <span class="comment">// nothing was mapped on this controller for this Action</span>
if(controller.templateCount == 0) return; <span class="comment">// this example only supports controllres that have Controller Templates</span>
IControllerTemplate template = controller.Templates[0]; <span class="comment">// just use the first template in the Controller</span>
<span class="comment">// Convert the Action Element Map into Controller Template Element Targets
// This gets what Controller Template Elements the Action Element Map is pointing to.
// Note that this may return two targets in some rare cases where the Action Element Map
// binds to multiple elements on the Template such as the Racing Wheel template which has
// Shifer 1-10 and Reverse Gear, two of which may be bound to the same Controller element.
// Two elements would also be returned if two Template Buttons are mapped to both poles of a single
// Controller Axis.</span>
<span class="comment"></span> if(template.GetElementTargets(aem, _tempTemplateElementTargets) == 0) return; <span class="comment">// no template targets found for the Action Element Map</span>
ControllerTemplateElementTarget target = _tempTemplateElementTargets[0]; <span class="comment">// just use the first target for this example</span>
<span class="comment">// Find the glyph for the element on the template</span>
Sprite glyph = ControllerTemplateGlyphs.GetGlyph(template.typeGuid, target.element.id, target.axisRange);
if(glyph == null) return; <span class="comment">// no glyph found</span>
<span class="comment">// Draw the glyph to the screen</span>
Rect rect = new Rect(0, 30, glyph.textureRect.width, glyph.textureRect.height);
GUI.Label(new Rect(rect.x, rect.y + rect.height + 20, rect.width, rect.height), action.descriptiveName);
GUI.DrawTexture(rect, glyph.texture);
}
}
}</pre>
<pre class="code"><span class="comment">// ControllerTemplateGlpyhs.cs</span>
using UnityEngine;
using System.Collections;
namespace Rewired.Demos {
using Rewired.Data.Mapping;
<span class="comment">// This is a basic example showing one way of storing glyph data for Controller Templates</span>
public class ControllerTemplateGlyphs : MonoBehaviour {
[SerializeField]
private ControllerTemplateEntry[] templates;
private static ControllerTemplateGlyphs Instance;
void Awake() {
Instance = this; <span class="comment">// set up a singleton</span>
}
public static Sprite GetGlyph(System.Guid templateGuid, int elementIdentifierId, AxisRange axisRange) {
if(Instance == null) return null;
if(Instance.templates == null) return null;
<span class="comment">// Try to find the glyph</span>
for(int i = 0; i < Instance.templates.Length; i++) {
if(Instance.templates[i] == null) continue;
if(Instance.templates[i].template == null) continue; <span class="comment">// no joystick assigned</span>
if(Instance.templates[i].template.Guid != templateGuid) continue; <span class="comment">// guid does not match</span>
return Instance.templates[i].GetGlyph(elementIdentifierId, axisRange);
}
return null;
}
[System.Serializable]
private class ControllerTemplateEntry {
public string name;
<span class="comment">// This must be linked to the HardwareJoystickTemplateMap located in Rewired/Internal/Data/Controllers/HardwareMaps/Joysticks/Templates</span>
public HardwareControllerTemplateMap template;
public GlyphEntry[] glyphs;
public Sprite GetGlyph(int elementIdentifierId, AxisRange axisRange) {
if(glyphs == null) return null;
for(int i = 0; i < glyphs.Length; i++) {
if(glyphs[i] == null) continue;
if(glyphs[i].elementIdentifierId != elementIdentifierId) continue;
return glyphs[i].GetGlyph(axisRange);
}
return null;
}
}
[System.Serializable]
private class GlyphEntry {
public int elementIdentifierId;
public Sprite glyph;
public Sprite glyphPos;
public Sprite glyphNeg;
public Sprite GetGlyph(AxisRange axisRange) {
switch(axisRange) {
case AxisRange.Full: return glyph;
case AxisRange.Positive: return glyphPos != null ? glyphPos : glyph;
case AxisRange.Negative: return glyphNeg != null ? glyphNeg : glyph;
}
return null;
}
}
}
}</pre>
<p><strong><a name="display-glyph-for-action-keyboard" id="display-glyph-for-action-keyboard"></a>Keyboard:</strong></p>
<p>The process is very similar to Joysticks, but complicated by the fact that a keyboard mapping may have up to 3 modifier keys as well as the primary key. Use the following properties on the ActionElementMap to determine to total binding:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ActionElementMap_keyboardKeyCode.htm">ActionElementMap.keyboardKeyCode</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ActionElementMap_modifierKey1.htm">ActionElementMap.modifierKey1</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ActionElementMap_modifierKey2.htm">ActionElementMap.modifierKey2</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ActionElementMap_modifierKey3.htm">ActionElementMap.modifierKey3</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ActionElementMap_modifierKeyFlags.htm">ActionElementMap.modifierKeyFlags</a></li>
</ul>
<p><a href="https://guavaman.com/rewired/files/docs/RewiredKeyboardElementIdentifiersCSV.zip">Download a CSV file of the current Keyboard element identifiers here</a>.</p>
<p><strong><a name="display-glyph-for-action-mouse" id="display-glyph-for-action-mouse"></a>Mouse:</strong></p>
<p>The process is essentially identical to Joysticks.</p>
<p><a href="https://guavaman.com/rewired/files/docs/RewiredMouseElementIdentifiersCSV.zip">Download a CSV file of the current Mouse element identifiers here</a>.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="display-glyph-for-active-elements" id="display-glyph-for-active-elements"></a>Displaying a glyph for the currently active Controller elements</h3>
<p><strong>As of Rewired 1.1.56.0, displaying glyphs can be more easily handled by using <a href="Glyphs.html">the built-in glyph system</a>. </strong>Specifically, <a href="Glyphs.html#unity-ui-controller-element-glyph">this component can display a glyph for a specific controller element.</a> You will still need to select the controller element(s) you want to display however, so the below information may be useful.</p>
<p>The following information is considered outdated, but remains for reference.</p>
<p>&nbsp;</p>
<hr style="width: 50%; margin: 0 auto;"/>
<p>&nbsp;</p>
<p>Very similar to <a href="#display-glyph-for-action">the previous example</a>, this is a slightly modified process:</p>
<pre class="code">using UnityEngine;
using System.Collections;
namespace Rewired.Demos {
public class ShowControllerGlyphs : MonoBehaviour {
<span class="comment">// Using OnGUI for Unity 4.3 compatibility
// You would probably want to use Unity UI in 4.6+ instead</span>
void OnGUI() {
ShowGlyphs();
}
void ShowGlyphs() {
<span class="comment"> // Get the Rewired Player</span>
Player p = ReInput.players.GetPlayer(0); <span class="comment">// just use Player 0 in this example</span>
<span class="comment">// Get the last active controller the Player was using</span>
Controller activeController = p.controllers.GetLastActiveController();
if(activeController == null) { <span class="comment">// player hasn't used any controllers yet</span>
<span class="comment">// No active controller, set a default</span>
if(p.controllers.joystickCount > 0) { <span class="comment">// try to get the first joystick in player</span>
activeController = p.controllers.Joysticks[0];
} else { <span class="comment">// no joysticks assigned, just get keyboard</span>
activeController = p.controllers.Keyboard;
}
}
<span class="comment">// Display glpyhs for all currently active controller elements</span>
if(activeController.type != ControllerType.Joystick) return; <span class="comment">// this example only shows joysticks, not keyboard/mouse/custom
</span>
int drawCount = 0;
<span class="comment"> // Display a glyph for each Action if mapped for this controller in the Player</span>
for(int i = 0; i < ReInput.mapping.Actions.Count; i++) {
ShowActiveActionSource(p, activeController, ReInput.mapping.Actions[i], ref drawCount);
}
}
void ShowActiveActionSource(Player p, Controller controller, InputAction action, ref int count) {
Joystick joystick = controller as Joystick;<span class="comment"> // make sure this is a joystick</span>
if(joystick == null) return;
float value = p.GetAxis(action.id);
if(value == 0.0f) return;
<span class="comment">// Find the element source</span>
if(!p.IsCurrentInputSource(action.id, controller.type, controller.id)) return; <span class="comment">// not a source of this action</span>
<span class="comment">// Get the sources contributing to this Action</span>
var sources = p.GetCurrentInputSources(action.id);
ActionElementMap aem = null;
<span class="comment">// Find the first source on this controller for the Action</span>
for(int i = 0; i < sources.Count; i++) {
if(sources[i].controller != controller) continue;
aem = sources[i].actionElementMap;
break; <span class="comment">// only show one source for now</span>
}
if(aem == null) return;
<span class="comment">// Find the glyph for the element on the controller</span>
Sprite glyph = ControllerGlyphs.GetGlyph(joystick.hardwareTypeGuid, aem.elementIdentifierId, aem.axisRange);
if(glyph == null) return; <span class="comment">// no glyph found</span>
<span class="comment">// Draw the glyph to the screen</span>
Rect rect = new Rect(count * 120, 30, glyph.textureRect.width, glyph.textureRect.height);
GUI.Label(new Rect(rect.x, rect.y + rect.height + 20, rect.width, rect.height), action.descriptiveName);
GUI.DrawTexture(rect, glyph.texture);
count++;
}
}
}</pre>
<p>&nbsp;</p>
<hr />
<h3><a name="get-mappings-for-joystick-not-attached" id="get-mappings-for-joystick-not-attached"></a>Getting Controller Maps for a Joystick not currently attached</h3>
<p>The previous methods for displaying glyphs and other mapping information require that the Joystick be attached to the system in order to look up the information. Sometimes you may want to display glyphs or other information about mappings for Joysticks that are not currently connected. The only way to do this is by loading Controller Map instances using the following methods to determine what the default mappings are for the controller in question when it is not present:</p>
<p>Joystick Maps:<br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_MappingHelper_GetJoystickMapInstance.htm">ReInput.mapping.GetJoystickMapInstance</a></p>
<p>Controller Template Maps:<br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_MappingHelper_GetControllerTemplateMapInstance.htm">ReInput.mapping.GetControllerTemplateMapInstance</a></p>
<p>If you need to display gylphs for saved user mappings:<br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_MappingHelper_GetJoystickMapInstanceSavedOrDefault.htm">ReInput.mapping.GetJoystickMapInstanceSavedOrDefault</a></p>
<p>Use the information from the returned maps to determine the mappings and display the information.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="get-contributing-input-sources" id="get-contributing-input-sources"></a>Getting contributing input sources for an Action</h3>
<p>You can get information about all the input sources currently contributing to the value of an <a href="Actions.html">Action</a> in a <a href="Players.html">Player</a>. There are several methods available to get this information:</p>
<ul>
<li> <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetCurrentInputSources.htm">Player.GetCurrentInputSources</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_IsCurrentInputSource.htm">Player.IsCurrentInputSource</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_InputActionEventData_GetCurrentInputSources.htm">InputActionEventData.GetCurrentInputSource</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_InputActionEventData_IsCurrentInputSource.htm">InputActionEventData.IsCurrentInputSource </a></li>
</ul>
<p>You can either retrieve a list of all input sources currently contributing to input or query whether a <a href="Controllers.html">Controller</a> type or an individual <a href="Controllers.html">Controller</a> contributed input.</p>
<p>You can get data about the current input sources and then use that to tell which <a href="Controllers.html">Controllers</a> or even which individual elements on the <a href="Controllers.html">Controllers</a> were used to provide the input in the current frame.</p>
<p>See <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_InputActionSourceData.htm">InputActionSourceData</a> for more information on data returned.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="last-used-controller" id="last-used-controller"></a>Determining which Controller was last used</h3>
<p>You can determine which <a href="Controllers.html">Controller</a> or what type of Controller was last used system-wide<a href="Players.html"></a> or by an individual <a href="Players.html">Player</a>. One common use of this technique is to switch on-screen glyphs depending on whether the user is using a mouse/keyboard or a <a href="Controllers.html#joysticks">Joystick</a>.</p>
<p>Use the following methods:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_ControllerHelper_GetLastActiveController.htm">ReInput.controllers.GetLastActiveController</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_ReInput_ControllerHelper_GetLastActiveControllerType.htm">ReInput.controllers.GetLastActiveControllerType</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_GetLastActiveController.htm">Player.controllers.GetLastActiveController</a></li>
</ul>
<p>The ReInput methods will get the last active controller of all controllers regardless of whether or not it is assigned to a Player or any of the elements have been mapped. This is most useful for one-player games.</p>
<p>The Player.controllers.GetLastActiveController method will get the last active controller used by that Player. Be aware that only mapped elements determine whether a Controller just became active. For example, if you're testing to see if the mouse is the last active controller, if nothing is mapped to the left mouse button and it is clicked, it will not be considered the last active controller in the Player.</p>
<p>Then you can get the <a href="Controllers.html">Controller</a> type from <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Controller_type.htm">Controller.type.</a></p>
<pre class="code">
<span class="comment">// Get last controller from a Player and the determine the type of controller being used</span>
Controller controller = player.controllers.GetLastActiveController();
if(controller != null) {
switch(controller.type) {
case ControllerType.Keyboard:
<span class="comment">// Do something for keyboard</span>
break;
case ControllerType.Joystick:
<span class="comment">// Do something for joystick</span>
break;
case ControllerType.Mouse:
<span class="comment">// Do something for mouse</span>
break;
case ControllerType.Custom:
<span class="comment">// Do something custom controller</span>
break;
}
}</pre>
<p>You can also subscribe to events instead of polling:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_ControllerHelper_AddLastActiveControllerChangedDelegate.htm">ReInput.controllers.AddLastActiveControllerChangedDelegate</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_ControllerHelper_RemoveLastActiveControllerChangedDelegate.htm">ReInput.controllers.RemoveLastActiveControllerChangedDelegate</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_ReInput_ControllerHelper_ClearLastActiveControllerChangedDelegates.htm">ReInput.controllers.ClearLastActiveControllerChangedDelegates</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_AddLastActiveControllerChangedDelegate.htm">Player.controllers.AddLastActiveControllerChangedDelegate</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_RemoveLastActiveControllerChangedDelegate.htm">Player.controllers.RemoveLastActiveControllerChangedDelegate</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Player_ControllerHelper_ClearLastActiveControllerChangedDelegates.htm">Player.controllers.ClearLastActiveControllerChangedDelegates</a></li>
</ul>
<p>&nbsp;</p>
<hr />
<h3><a name="is-controller-gamepad" id="is-controller-gamepad"></a>Determining if a Controller is a Gamepad</h3>
<p>All <a href="SupportedControllers.html">recognized gamepads</a> implement the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_IGamepadTemplate.htm">IGamepadTemplate</a> <a href="ControllerTemplates.html">Controller Template</a>. See <a href="ControllerTemplates.html#determining-if-controller-implements-template">Controller Templates - Determining if a Controller implements a particular Controller Template</a> for more information.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="relative-absolute-axes" id="relative-absolute-axes"></a>Handling Mouse and Joystick axes</h3>
<ul>
<li>Mouse axes always return Relative values (change in value since the last frame) unless the Input Behavior Mouse X/Y Axis Mode or Mouse Other Axis Mode has been set to &quot;Digital Axis&quot;. Relative axes should never be multiplied by Time.deltaTime.</li>
<li>Joystick and Keyboard axes always return Absolute values (an absolute value from -1 to +1). Absolute axis values must be multiplied by Time.deltaTime.</li>
<li>Custom Controller axes can return Relative or Absolute values depending on how you configured the axis.</li>
</ul>
<p><strong>Determining which type of axis is being used for an Action</strong></p>
<p>You have your choice of how to handle this. Do one of the following:</p>
<ol>
<li>Check the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetAxisCoordinateMode.htm">player.GetAxisCoordinateMode</a> method for the Action to determine if it's a relative or absolute axis.</li>
<li>Check the <a href="#last-used-controller">last used controller type</a> to determine whether it's a mouse or other device type being used.</li>
<li>Create separate Actions for Mouse axes and Joystick axes.</li>
</ol>
<p><strong>Using the same code for Mouse and Joystick axes</strong></p>
<p>It's possible to use the exact same code to process both Absolute and Relative axes by first processing Absolute values into Relative values. This can be done by simply multiplying the value by Time.deltaTime and a base speed constant. For example, getting all axis values through this method will result in axis values that are processed to be Relative. Then your code can just be written to expect only Relative values:</p>
<pre class="code">public static float GetAxisRelative(this Rewired.Player player, int actionId, float absoluteToRelMult) {
float value = player.GetAxis(actionId);
if(player.GetAxisCoordinateMode(actionId) == Rewired.AxisCoordinateMode.Absolute) value *= Time.unscaledDeltaTime * absoluteToRelMult;
return value;
}</pre>
<p>&nbsp;</p>
<hr />
<h3><a name="calibrating-controller-axes" id="calibrating-controller-axes"></a>Calibrating Joystick axes</h3>
<p>The general process of calibrating <a href="Controllers.html#joysticks">Joystick</a><a href="Controllers.html"></a> axes is as follows:</p>
<ol>
<li><a href="#get-controller">Get the Joystick.</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ControllerWithAxes_calibrationMap.htm">Get the Calibration Map from the Joystick.</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_CalibrationMap_GetAxis.htm">Get the AxisCalibration for the Axis from the Calibration Map.</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_AxisCalibration.htm">Set the calibrated values in the AxisCalibration object.</a></li>
</ol>
<p>You can see an example of axis calibration in Rewired/Examples/ControlRemapping1.</p>
<p><strong>Enabled</strong><br />
The enabled state of the Axis can be set with the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_AxisCalibration_enabled.htm">AxisCalibration.enabled</a> property. Disabled Axes always return 0.</p>
<p><strong>Dead zone</strong><br />
The dead zone of the Axis can be set with the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_AxisCalibration_deadZone.htm">AxisCalibration.deadZone</a> property. If the Axis's absolute value is less than or equal to the dead zone, it will return 0.</p>
<p><strong>Min, max, zero</strong><br />
The Axis's value can be converted to a new range using the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_AxisCalibration_calibratedMin.htm">AxisCalibration.calibratedMin</a>, <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_AxisCalibration_calibratedMax.htm">AxisCalibration.calibratedMax</a>, and <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_AxisCalibration_calibratedZero.htm">AxisCalibration.calibratedZero</a> properties. These can be used to transform the value of an Axis such as a gamepad trigger that returns -1 at a resting state into a more useful range of 0 when at rest, 1 when fully pressed. If <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_AxisCalibration_applyRangeCalibration.htm">AxisCalibration.applyRangeCalibration</a> is set to false, these transformations will not be applied.</p>
<p><strong>Invert</strong><br />
If <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_AxisCalibration_invert.htm">AxisCalibration.invert</a> is set to true, the final value will be multiplied by -1. This can be used to correct an inverted Axis.<br />
</p>
<p><strong>Sensitivity</strong><br />
In order to set axis sensitivity, you must set the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_AxisCalibration_sensitivityType.htm">AxisCalibration.sensitivityType</a> to determine how it will be calculated. If <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_AxisCalibration_sensitivityType.htm">AxisCalibration.sensitivityType</a> is set to Multiplier
or Power, the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_AxisCalibration_sensitivity.htm">AxisCalibration.sensitivity</a> property is used to calculate the value. If <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_AxisCalibration_sensitivityType.htm">AxisCalibration.sensitivityType</a> is set to Curve, the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_AxisCalibration_sensitivityCurve.htm">AxisCalibration.sensitivityCurve</a> property is used to calculate the value.<br />
</p>
<p><strong>Useful API Reference:</strong></p>
<p><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_CalibrationMap.htm">CalibrationMap<br />
</a><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_AxisCalibration.htm">AxisCalibration</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_AxisCalibrationData.htm">AxisCalibrationData</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ControllerWithAxes_calibrationMap.htm">Joystick.calibrationMap<br />
</a><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_CalibrationMapSaveData.htm">CalibrationMapSaveData</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Joystick_GetCalibrationMapSaveData.htm">Joystick.GetCalibrationMapSaveData</a></p>
<p>&nbsp;</p>
<hr />
<h3><a name="Vibration-Rumble" id="Vibration-Rumble"></a>Vibration/Rumble</h3>
<p>Rewired supports vibration on compatible controllers on certain platforms. <a href="FAQ.html#force-feedback">See this for more information</a>.</p>
<p>Important: You must have XInput enabled in the Rewired Input Manager on the Windows Standalone platform for Xbox 360 controller vibration support.</p>
<p>There are two ways you can set vibration.</p>
<ol>
<li>Through the <a href="Players.html">Player</a>.</li>
<li>Through the <a href="Controllers.html#joysticks">Joystick</a>(s).</li>
</ol>
<p>Setting vibration through the Player allows you to set vibration on all Joysticks assigned to that Player simultaneously.</p>
<pre class="code">
<span class="comment">// Set vibration in all Joysticks assigned to the Player</span>
int motorIndex = 0; <span class="comment">// the first motor</span>
float motorLevel = 1.0f; <span class="comment">// full motor speed</span>
float duration = 2.0f; <span class="comment">// 2 seconds</span>
player.SetVibration(motorIndex, motorLevel, duration);</pre>
<p>To set vibration in the Joystick(s), just get them from the Player class and set the motor levels on
each of them. </p>
<pre class="code">
<span class="comment">// Set vibration by motor type</span>
foreach(Joystick j in player.controllers.Joysticks) {
if(!j.supportsVibration) continue;
j.SetVibration(leftMotorValue, rightMotorValue);
}
<span class="comment">// Set vibration by motor index</span>
foreach(Joystick j in player.controllers.Joysticks) {
if(!j.supportsVibration) continue;
if(j.vibrationMotorCount &gt; 0) j.SetVibration(0, leftMotorValue);
if(j.vibrationMotorCount &gt; 1) j.SetVibration(1, rightMotorValue);
}
<span class="comment">// Set vibration for a certain duration</span>
foreach(Joystick j in player.controllers.Joysticks) {
if(!j.supportsVibration) continue;
if(j.vibrationMotorCount &gt; 0) j.SetVibration(0, leftMotorValue, 1.0f); <span class="comment">// 1 second duration</span>
}
<span class="comment">// Stop vibration</span>
foreach(Joystick j in player.controllers.Joysticks) {
j.StopVibration();
}</pre>
<p>This would set vibration on all <a href="Controllers.html#joysticks">Joysticks</a><a href="Controllers.html"></a> assigned to the <a href="Players.html">Player</a>.</p>
<p>There are also these functions/properties in the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Joystick.htm">Joystick</a> class:<br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/F_Rewired_Joystick_supportsVibration.htm">Joystick.supportsVibration</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Joystick_vibrationMotorCount.htm">Joystick.vibrationMotorCount</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Joystick_GetVibration.htm">Joystick.GetVibration</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Joystick_SetVibration.htm">Joystick.SetVibration</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Joystick_StopVibration.htm">Joystick.StopVibration</a><br/>
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Joystick_vibrationLeftMotor.htm">Joystick.vibrationLeftMotor</a><br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Joystick_vibrationRightMotor.htm">Joystick.vibrationRightMotor</a></p>
<p>&nbsp;</p>
<hr />
<h3><a name="button-press-types" id="button-press-types"></a>Handling button presses of various types</h3>
<p>Rewired has a number of methods for handling button presses in a variety of ways.</p>
<p><strong>Most Common:</strong></p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButton.htm">Player.GetButton</a>: Gets the button held state of an Action. This will return TRUE as long as the button is held. This also applies to axes being used as buttons.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonDown.htm">Player.GetButtonDown</a>: Gets the button just pressed state of an Action. This will only return TRUE only on the first frame the button is pressed or for the duration of the Button Down Buffer time limit if set in the Input Behavior assigned to this Action. This also applies to axes being used as buttons.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonUp.htm">Player.GetButtonUp</a>: Get the button just released state for an Action. This will only return TRUE for the first frame the button is released. This also applies to axes being used as buttons.</li>
</ul>
<p><strong>Double Press:</strong></p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonDoublePressHold.htm">Player.GetButtonDoublePressHold</a>: Gets the button double pressed and held state of an Action. This will return TRUE after a double press and the button is then held.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonDoublePressDown.htm">Player.GetButtonDoublePressDown</a>: Gets the button double pressed state of an Action. This will return TRUE only on the first frame of a double press.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonDoublePressUp.htm">Player.GetButtonDoublePressUp</a>: Gets the button double pressed and just released state of an Action. This will return TRUE only on the first frame after a double press is released.</li>
</ul>
<p><strong>Single Press:</strong></p>
<p>These methods should only be used if you need to detect both a single press and a double press on the same Action because they only return true after a delay.</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonSinglePressHold.htm">Player.GetButtonSinglePressHold</a>: Gets the button single pressed and held state of an Action. This will return TRUE after a button is held and the double press timeout has expired. This will never return TRUE if a double press occurs. This method is delayed because it only returns TRUE after the double press timeout has expired. Only use this method if you need to check for both a single press and a double press on the same Action. Otherwise, use GetButton instead for instantaneous button press detection. The double press speed is set in the Input Behavior assigned to the Action.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonSinglePressDown.htm">Player.GetButtonSinglePressDown</a>: Gets the button just single pressed and held state of an Action. This will return TRUE for only the first frame after a button press and after the double press timeout has expired. This will never return TRUE if a double press occurs. This method is delayed because it only returns TRUE after the double press timeout has expired. Only use this method if you need to check for both a single press and a double press on the same Action. Otherwise, use GetButtonDown instead for instantaneous button press detection. The double press speed is set in the Input Behavior assigned to the Action.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonSinglePressUp.htm">Player.GetButtonSinglePressUp</a>: Gets the button single pressed and just released state of an Action. This will return TRUE for only the first frame after the release of a single press. This will never return TRUE if a double press occurs. This method is delayed because it only returns TRUE after the double press timeout has expired. Only use this method if you need to check for both a single press and a double press on the same Action. Otherwise, use GetButtonUp instead for instantaneous button press detection. The double press speed is set in the Input Behavior assigned to the Action.</li>
</ul>
<p><strong>Timed Presses:</strong></p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonTimedPress.htm">Player.GetButtonTimedPress</a>: Gets the button held state of an Action after being held for a period of time. This will return TRUE only after the button has been held for the specified time and will continue to return TRUE until the button is released. This also applies to axes being used as buttons.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonTimedPressDown.htm">Player.GetButtonTimedPressDown</a>: Gets the button state of an Action after being held for a period of time. This will return TRUE only on the frame in which the button had been held for the specified time. This also applies to axes being used as buttons.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonTimedPressUp.htm">Player.GetButtonTimedPressUp</a>: Gets the button state of an Action after being held for a period of time and then released. This will return TRUE only on the frame in which the button had been held for at least the specified time and then released. This also applies to axes being used as buttons.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonShortPress.htm">Player.GetButtonShortPress</a>: Gets the button held state of an Action after being held for a period of time. This will return TRUE only after the button has been held for the specified time and will continue to return TRUE until the button is released. This also applies to axes being used as buttons. The button short press time is set in the Input Behavior assigned to the Action. For a custom duration, use GetButtonTimedPress instead.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonShortPressDown.htm">Player.GetButtonShortPressDown</a>:
Gets the button state of an Action after being held for a period of time. This will return TRUE only on the frame in which the button had been held for the specified time. This also applies to axes being used as buttons. The button short press time is set in the Input Behavior assigned to the Action. For a custom duration, use GetButtonTimedPressDown instead.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonShortPressUp.htm">Player.GetButtonShortPressUp</a>: Gets the button state of an Action after being held for a period of time and then released. This will return TRUE only on the frame in which the button had been held for at least the specified time and then released. This also applies to axes being used as buttons. The button short press time is set in the Input Behavior assigned to the Action. For a custom duration, use GetButtonTimedPressUp instead.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonLongPress.htm">Player.GetButtonLongPress</a>: Gets the button held state of an Action after being held for a period of time. This will return TRUE only after the button has been held for the specified time and will continue to return TRUE until the button is released. This also applies to axes being used as buttons. The button long press time is set in the Input Behavior assigned to the Action. For a custom duration, use GetButtonTimedPress instead.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonLongPressDown.htm">Player.GetButtonLongPressDown</a>: Gets the button state of an Action after being held for a period of time. This will return TRUE only on the frame in which the button had been held for the specified time. This also applies to axes being used as buttons. The button long press time is set in the Input Behavior assigned to the Action. For a custom duration, use GetButtonTimedPressDown instead.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonLongPressUp.htm">Player.GetButtonLongPressUp</a>: Gets the button state of an Action after being held for a period of time and then released. This will return TRUE only on the frame in which the button had been held for at least the specified time and then released. This also applies to axes being used as buttons. The button long press time is set in the Input Behavior assigned to the Action. For a custom duration, use GetButtonTimedPressUp instead.</li>
</ul>
<p><strong>Tap / Press:</strong></p>
<p>To differentiate between a short tap and a longer press, simply use a combination of <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonTimedPressUp.htm">Player.GetButtonTimedPressUp</a> and <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonTimedPressDown.htm">Player.GetButtonTimedPressDown</a>. For example:</p>
<pre class="code">
if(player.GetButtonTimedPressUp("Action", 0f, 0.7f)) { <span class="comment">// button was released in 0.7 seconds or less</span>
<span class="comment">// This is a tap</span>
} else if(player.GetButtonTimedPressDown("Action", 0.7f)) { <span class="comment">// button was pressed for 0.7 seconds</span>
<span class="comment">// This is a press</span>
}</pre>
<p><strong>Repeating:</strong></p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonRepeating.htm">Player.GetButtonRepeating</a>: Gets the repeating button state of an Action. This will return TRUE when immediately pressed, then FALSE until the Input Behaviour button repeat delay has elapsed, then TRUE for a 1-frame duration repeating at the interval specified in the Input Behavior assigned to the Action. This also applies to axes being used as buttons.</li>
</ul>
<p><strong>History:</strong></p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonPrev.htm">Player.GetButtonPrev</a>: Gets the button held state of an Action during the previous frame.</li>
</ul>
<p><strong>Time Information:</strong></p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonTimePressed.htm">Player.GetButtonTimePressed</a>: Gets the length of time in seconds that a button has been continuously held down. Returns 0 if the button is not currently pressed.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_GetButtonTimeUnpressed.htm">Player.GetButtonTimeUnpressed</a>: Gets the length of time in seconds that a button has not been pressed. Returns 0 if the button is currently pressed.</li>
</ul>
<p><strong><a name="button-press-types-negative-buttons" id="button-press-types-negative-buttons"></a>Negative Buttons:</strong></p>
<p>Each of the methods above also has a corresponding Negative Button method which is named the same except with NegativeButton in place of Button. These serve to allow you to use axes as buttons and will trigger when the negative side of the axis is activated while the standard Button version will trigger only when the positive side of the axis is activated. However, it is usually easier to just map each pole of the axis to a seperate Action (split axis) so that each Action can just be queried with GetButton.</p>
<p>If you want all GetButton calls to return True when either the positive or negative side of the axis is activated, enable the option <a href="RewiredEditor.html#settings-activate-action-buttons-on-negative-value">&quot;Activate Action Buttons on Negative Values&quot; in the Rewired Editor</a>.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="button-combos" id="does-rewired-support-x-controller4"></a>Handling multi-button Actions</h3>
<p>Rewired does not currently have a way to bind multiple <a href="Controllers.html">Controller</a> elements to a single <a href="Actions.html">Action</a> except for keyboard modifier keys and indirectly through the use of <a href="CustomControllers.html">Custom Controllers</a>. To handle button combos, they should be handled in code based on your individual needs (timings, which needs to be pressed first, what cancels what out, etc). In these cases, it can help to think of it as if you're using <a href="Actions.html">Actions</a> as buttons:</p>
<pre class="code">
<span class="comment">// This example shows a simple handling of a 2-button combo where the
// modifier button must be held down and the primary button pressed</span>
bool modifier = player.GetButton(&quot;ModifierAction&quot;); <span class="comment">// get the &quot;held&quot; state of the button</span>
bool primary = player.GetButtonDown(&quot;PrimaryAction&quot;); <span class="comment">// get the &quot;just pressed&quot; state of the button</span>
if(modifier &amp;&amp; primary) { <span class="comment">// modifier was held or just pressed and primary was just pressed</span>
<span class="comment">// Do something</span>
}</pre>
<p>The constituent <a href="Actions.html">Actions</a> can be remapped by the user freely and nothing breaks. You also don't have to worry about the complexities of trying to allow the user to remap actual physical button combos for an <a href="Actions.html">Action</a> and worrying about what else may already mapped to the constituent buttons. In addition, this kind of <a href="Actions.html">Action</a> combo will work across multiple <a href="Controllers.html">Controllers</a> and <a href="Controllers.html">Controller</a> types since Rewired's <a href="Players.html">Player</a>-based input system is largely controller agnostic.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="excluding-players-from-joystick-assignment" id="excluding-players-from-joystick-assignment"></a>Excluding certain Players from Joystick auto-assignment</h3>
<p>The <a href="Controllers.html#joystick-auto-assignment">joystick auto-assignment system</a> has a number of options available, including the option to exclude certain Players from auto-assignment. The &quot;Exclude from Joy Auto Assign&quot; checkbox <a href="RewiredEditor.html#Players">on the Player in the Rewired Editor</a> allows you to selectively disable joystick auto-assignment for certain Players. Additionally, this can be set in scripting with the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Player_ControllerHelper_excludeFromControllerAutoAssignment.htm">player.controllers.excludeFromControllerAssignment</a> property.</p>
<p>Also, the Settings page of the Rewired Editor has <a href="RewiredEditor.html#settings-joystick-auto-assignment">a number of options which can be set for Joystick auto-assignment</a>. The &quot;Assign to Playing Players Only&quot; option allows to you exclude Players who are not currently playing or have been disabled by setting the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Player_isPlaying.htm">Player.isPlaying</a> property to False.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="changing-configuration-settings-at-runtime" id="changing-configuration-settings-at-runtime"></a>Changing configuration settings at runtime</h3>
<p>Most configuration settings can be changed at runtime through ReInput.configuration. Please see the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ReInput_ConfigHelper.htm">ReInput.ConfigHelper API reference</a> for more information.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="simulating-input" id="simulating-input"></a>Simluating Input</h3>
<p>You can inject your own input values into the Player-Action system is through the use of <a href="CustomControllers.html">Custom Controllers</a>. See the <a href="CustomControllers.html">Custom Controllers</a> documentation for more information.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="converting-scripts" id="converting-scripts"></a>Converting scripts from UnityEngine.Input to Rewired</h3>
<p><strong>IMPORTANT:</strong> This documentation applies to scripts that were written for the legacy UnityEngine.Input system. This does not apply to scripts written for Unity's new Input System.</p>
<p><strong>Unity Input Override (the easy way):</strong></p>
<p> Rewired includes the <a href="UnityInputOverride.html">Unity Input Override</a> script to make converting most scripts from Unity input to Rewired effortless and automatic, requiring no code changes to work. It even works with most assets downloaded from the Unity Asset Store. <a href="UnityInputOverride.html">See Unity Input Override for more information</a>.</p>
<p><strong>Modifying script code to use Rewired instead of Unity input (the harder way):</strong></p>
<p>Converting a script from UnityEngine.Input is a very straightforward process for a single player game. For a quick conversion, simply do two find and replace operations:</p>
<ul>
<li> &quot;Input.GetButton&quot; -&gt; &quot;Rewired.ReInput.players.GetPlayer(0).GetButton&quot;</li>
<li>&quot;Input.GetAxis&quot; -&gt; &quot;Rewired.ReInput.players.GetPlayer(0).GetAxis&quot;</li>
</ul>
<p>This will get the value of each <a href="Actions.html">Action</a> from Player 0 for all GetButton, GetButtonDown, GetButtonUp, GetAxis, and GetAxisRaw calls.</p>
<p>You will also need to create the <a href="Actions.html">Actions</a> in the Rewired Input Manager that match the string names expected in the code. And of course you will have to create <a href="ControllerMaps.html">Keyboard, Mouse, Joystick, and/or Custom Controller Maps</a> and assign them to <a href="Players.html">Players</a> as is standard Rewired practice.</p>
<p>Mouse Sensitivity: If the script you are using processes Mouse X/Y axis values such as a mouse-look script, be sure to <a href="RewiredEditor.html#InputBehaviors">set the Mouse XY Axis Sensitivity in the Input Behavior</a> assigned to the Actions to 0.1 instead of Rewired's default value of 1. Unity defaults to 0.1 sensitivity for mouse axes, so you should change this value to match if you want the scripts to behave the same way they would when using Unity input.</p>
<p>If your code has Input.GetKey calls, if you want those to instead use Rewired <a href="Actions.html">Actions</a>, you will want to change these to &quot;Rewired.ReInput.players.GetPlayer(0).GetButton&quot; and replace the Unity KeyCode with the name or id of the <a href="Actions.html">Action</a> you want to use.</p>
<p>You could also cache the <a href="Players.html">Player</a> object on Awake for the <a href="Players.html">Player</a> in question and use that variable in the find/replace operation, but the above example provides a quick method to convert most scripts that use UnityEngine.Input to Rewired.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="exporting-constants" id="converting-scripts3"></a>Exporting constants for use in scripting</h3>
<p>On the <a href="RewiredEditor.html#Tools">Rewired Input Manager -&gt; Tools page</a>, the section &quot;Export Constants&quot; allows you to export all <a href="Actions.html">Actions</a>, <a href="MapCategories.html">Map Categories</a>, and <a href="Layouts.html">Layouts</a>, to a CS file containing a list of constants. For example, this allows you to use Rewired <a href="Actions.html">Actions</a> in scripts without having to type in strings which are prone to typos, plus it allows you take advantage of auto-complete in your IDE. Using constants is also more efficient because integer comparison is faster than string comparison.</p>
<p>Note: The exported constants will only be valid for the Rewired Input Manager from which they were exported. If you have multiple different Rewired Input Managers with different input configurations, you will have to export from both and use a different parent class name for each so they don't conflict. Also, if you add or delete any relevant items in the Rewired Input Manager, the constant list must be exported again.</p>
<pre class="code">
<span class="comment">// The Action id constants can be used in place of strings throughout the Rewired API</span>
void Update() {
Player player = ReInput.players.GetPlayer(0);
bool fire = player.GetButton(RewiredConsts.Action.Fire) <span class="comment">// get the value of &quot;Fire&quot; by using the Action id constant instead of a string</span>
}</pre>
<p>&nbsp;</p>
<hr />
<h3><a name="actionid-property-drawer" id="converting-scripts2"></a>Displaying a drop-down list of Actions in the inspector of a script</h3>
<p>You can display a list of Rewired <a href="Actions.html">Actions</a> in a MonoBehaviour script by using the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ActionIdPropertyAttribute.htm">ActionIdPropertyAttribute</a> which will automatically create a Unity property drawer in the inspector.</p>
<p><img src="files/images/howtos_actionidproperty.png" alt="ActionIdProperty" /></p>
<p>There are two steps:</p>
<ol>
<li><a href="#exporting-constants">Export a list of Action id constants from the Rewired Input Manager</a></li>
<li>Create a public integer field in your script and add the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ActionIdPropertyAttribute.htm">ActionIdProperty</a> attribute</li>
</ol>
<p><strong>Using the ActionIdProperty attribute</strong></p>
<p>In your MonoBehaviour script, create an integer field (or array/list) and add the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ActionIdPropertyAttribute.htm">ActionIdProperty</a> attribute above it. You must pass this attribute a class Type that contains a list of public integer constants. Each constant will be displayed in the drop-down list.</p>
<p>Optional: You can also pass <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ActionIdPropertyAttribute.htm">ActionIdProperty</a> an integer Enum type and it will display each item in the enumeration. The drawback of using Enums is that you will have to cast the enum value to an int each time you want to use it in the Rewired API.</p>
<pre class="code">using UnityEngine;
using Rewired;
public class MyClass : MonoBehaviour {
<span class="comment">// This attribute denotes this int field as a Rewired Action Id property and will display a drop-down list</span>
<span class="comment">// The class RewiredActions was exported from the Rewired Input Manager and contains a list of Action id constants</span>
[ActionIdProperty(typeof(RewiredConsts.Action))]
public int rewiredAction1;
void Update() {
Player p = ReInput.players.GetPlayer(0);
if(rewiredAction1 >= 0) { <span class="comment">// make sure the Action id is valid before using it because None = -1</span>
if(p.GetButton(rewiredAction1)) { <span class="comment">// get the button value for the Action</span>
Debug.Log("Pressed: " + ReInput.mapping.GetAction(rewiredAction1).name); <span class="comment">// log the name of the Action</span>
}
}
}
}</pre>
<p><strong>IMPORTANT:</strong></p>
<p>ActionIdProperty attribute is not compatible with the constant export setting &quot;Create Action Category Classes.&quot; This option creates additional sub classes for each Action Category. The property drawer does not have the capability of drilling down multiple class levels to find constants to generate the list.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="press-start-to-join" id="press-start-to-join"></a>Implementing a &quot;Press Start to Join&quot; Joystick assignment system</h3>
<p>Normally, Rewired will assign <a href="Controllers.html#joysticks">Joysticks</a><a href="Controllers.html"></a> to <a href="Players.html">Players</a> when each controller<a href="Controllers.html"></a> is detected based on settings in the Rewired Input Manager -&gt; Settings page. This will assign a <a href="Controllers.html#joysticks">Joystick</a><a href="Controllers.html"></a> to each <a href="Players.html">Player</a> in order as they become available so that the first <a href="Controllers.html#joysticks">Joystick</a> is assigned to Player 0, the second to Player 1, and so on. But the question has come up many times as to how to be able to let users just pick up any attached controller and press &quot;Start&quot;, then have that player join as the next available <a href="Players.html">Player</a> with that <a href="Controllers.html#joysticks">Joystick</a><a href="Controllers.html"></a> assigned. This kind of assignment method isn't as straightforward to implement.</p>
<p>First you should understand a little bit how <a href="ControllerMaps.html">Controller Maps</a> work. <a href="ControllerMaps.html">Controller maps</a> are loaded by the <a href="Players.html">Player</a>, not the <a href="Controllers.html">Controller</a>, therefore there is no <a href="Actions.html">Action</a> named &quot;Start&quot; in the <a href="Controllers.html#joysticks">Joystick</a> from which to generate input unless you assign that <a href="Controllers.html#joysticks">Joystick</a><a href="Controllers.html"></a> to a <a href="Players.html">Player</a> first. Because of this, you cannot simply ask each unassigned <a href="Controllers.html#joysticks">Joystick</a><a href="Controllers.html"></a> for the value of &quot;Start&quot; to determine if a player wants to join because it doesn't have access to any <a href="ControllerMaps.html">Controller Maps</a>.<br />
</p>
<p>There are various ways this assignment scheme can be achieved. Each method has its own advantages and disadvantages. Please read through all examples and decide which is most appropriate for your game before choosing a method.</p>
<ul>
<li><a href="#press-start-to-join-variable-player">Method 1: Using a variable Rewired.Player as an input source for your own Player object</a></li>
<li><a href="#press-start-to-join-any-button">Method 2: Easy but does not detect &quot;Start&quot;, only any button press</a></li>
<li><a href="#press-start-to-join-detect-start-manually">Method 3: Detect "Start" button press manually</a></li>
<li><a href="#press-start-to-join-poll-button-by-index">Method 4: Poll a specific button by index on a specific controller</a></li>
<li><a href="#press-start-to-join-controller-template">Method 5: Poll a specific button on a Controller Template</a></li>
</ul>
<p>&nbsp;</p>
<p><strong><a name="press-start-to-join-method-1" id="press-start-to-join-method-1"></a><a name="press-start-to-join-variable-player" id="press-start-to-join-variable-player"></a>Method 1: Using a variable Rewired.Player as an input source for your own Player object.</strong></p>
<p>An <a href="Examples.html#press-start-to-join">example is included with Rewired</a> showing the concept in action.<br />
</p>
<ol>
<li>Make your <a href="Players.html">Players</a> (let's say Player 0 3) in the editor.</li>
<li>Assign them all <a href="ControllerMaps.html">Joystick Maps</a> for the<a href="Controllers.html#joysticks">Joysticks</a> you want to support.</li>
<li>Create a &ldquo;Start&rdquo; action and be sure it is assigned in the <a href="ControllerMaps.html">Joystick Maps</a> you assigned to the <a href="Players.html">Players</a> on some button -- preferably, multiple buttons just to be sure in case a particular <a href="Controllers.html#joysticks">Joystick</a> has no Start button (or &ldquo;Center 2&rdquo; as defined in the <a href="https://guavaman.com/projects/rewired/docs/ControllerMaps.html#gamepad-template" target="_blank" rel="nofollow">Gamepad Template</a>.) A safe bet would be to put it on &ldquo;Center 2&rdquo; and &ldquo;Action Bottom Row 1&rdquo; for the Gamepad Template, and Button 0 on <a href="https://guavaman.com/projects/rewired/docs/ControllerMaps.html#unknown-controllers" target="_blank" rel="nofollow">Unknown Controller</a> (if you're defining an Unknown Controller Map).</li>
<li>Leave <a href="Controllers.html#joysticks">Joystick</a> auto-assignment enabled. Rewired will give each <a href="Players.html">Rewired.Player</a> a <a href="Controllers.html#joysticks">Joystick</a> if available.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ReInput_PlayerHelper_Players.htm" target="_blank" rel="nofollow">Loop through all Rewired.Players</a> and check for player.GetButtonDown(&ldquo;Start&rdquo;).</li>
<li>Now in your game code, simply assign whichever <a href="Players.html">Rewired.Player</a> returned TRUE to your game-side player object. Your game-side player object may be Player[0], but the <a href="Players.html">Rewired.Player</a> doesn&rsquo;t have to be. The user could press a button on the <a href="Controllers.html#joysticks">Joystick</a> assigned to Rewired.Player[3], but you can still then use Rewired.Player[3] as the input source for your game-side Player[0].</li>
</ol>
<p><br />
If you also support Keyboard and Mouse, at that point you might want to go ahead and load the appropriate keyboard map <a href="Layouts.html">Layouts</a> for your Player[0] into Rewired.Player[3]. This works best if keyboard <a href="Layouts.html">Layouts</a> for the various in-game players will be fixed. IE: Player 1 always uses the WASD set, Player 2 always uses JIKM, etc. (There are ways to make this assignment dynamic too but that's not covered here.)</p>
<p>The following code shows an example of one implmentation of Method 1:</p>
<pre class="code">
<span class="comment">/* Prerequisites:<br /> * 1. Create &quot;JoinGame&quot; Action.<br /> * 2. Create Map Categories &quot;Assignment&quot; and &quot;UI&quot;.<br /> * 3. Create Joystick and Keyboard Maps in the &quot;Assignment&quot; category that map &quot;JoinGame&quot;<br /> * to some buttons/keys such as &quot;Start&quot; on in the Gamepad Template and &quot;Space&quot;<br /> * and/or &quot;Enter&quot; in the Keyboard Map.<br /> * 4. Create Joystick and Keyboard Maps in the &quot;UI&quot; category for controlling the UI.<br /> * 5. Assign the &quot;Assignment&quot; maps to each Player (assign the Keyboard Map to only 1 Player unless you've<br /> * created multiple in different layouts for each Player to use). Ensure they are set to be enabled on start.<br /> * 6. Assign the &quot;UI&quot; maps to each Player setting them to be disabled on start.<br /> * 7. Leave joystick auto-assignment enabled.<br /> */</span>
using UnityEngine;
using System.Collections.Generic;
namespace Rewired.Demos {
using Rewired;
public class PressStartToJoinPlayerSelector : MonoBehaviour {
public int maxPlayers = 4;
private List<PlayerMap>&lt;PlayerMap&gt; playerMap; <span class="comment">// Maps Rewired Player ids to game player ids</span>
private int gamePlayerIdCounter = 0;
void Awake() {
playerMap = new List<PlayerMap>&lt;PlayerMap&gt;();
}
void Update() {
<span class="comment">// Watch for JoinGame action in each Player</span>
for(int i = 0; i < ReInput.players.playerCount; i++) {
if(ReInput.players.GetPlayer(i).GetButtonDown("JoinGame")) {
AssignNextPlayer(i);
}
}
}
void AssignNextPlayer(int rewiredPlayerId) {
if(playerMap.Count >= maxPlayers) {
Debug.LogError("Max player limit already reached!");
return;
}
int gamePlayerId = GetNextGamePlayerId();
<span class="comment">// Add the Rewired Player as the next open game player slot</span>
playerMap.Add(new PlayerMap(rewiredPlayerId, gamePlayerId));
Player rewiredPlayer = ReInput.players.GetPlayer(rewiredPlayerId);
<span class="comment">// Disable the Assignment map category in Player so no more JoinGame Actions return</span>
rewiredPlayer.controllers.maps.SetMapsEnabled(false, "Assignment");
<span class="comment">// Enable UI control for this Player now that he has joined</span>
rewiredPlayer.controllers.maps.SetMapsEnabled(true, "UI");
Debug.Log("Added Rewired Player id " + rewiredPlayerId + " to game player " + gamePlayerId);
}
private int GetNextGamePlayerId() {
return gamePlayerIdCounter++;
}
<span class="comment">// This class is used to map the Rewired Player Id to your game player id</span>
private class PlayerMap {
public int rewiredPlayerId;
public int gamePlayerId;
public PlayerMap(int rewiredPlayerId, int gamePlayerId) {
this.rewiredPlayerId = rewiredPlayerId;
this.gamePlayerId = gamePlayerId;
}
}
}
}</pre>
<p>&nbsp;</p>
<p><strong><a name="press-start-to-join-method-2" id="press-start-to-join-method-2"></a><a name="press-start-to-join-any-button" id="press-start-to-join-any-button"></a>Method 2: Easy but does not detect &quot;Start&quot;, only any button press:</strong></p>
<p>An <a href="Examples.html#press-any-button-to-join">example is included with Rewired</a> showing the concept in action.</p>
<ol>
<li><a href="RewiredEditor.html#settings">Disable Joystick auto-assignment</a> in the Rewired Editor.</li>
<li>In your script, <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ReInput_ControllerHelper_Joysticks.htm" target="_blank" rel="nofollow">iterate over all Joysticks</a> and check for <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Controller_GetAnyButtonDown.htm" target="_blank">any button press</a>.</li>
<li><a href="#assigning-joysticks">Assign that Joystick</a> to the first <a href="Players.html">Player</a>.</li>
</ol>
<p>&nbsp;</p>
<p><strong><a name="press-start-to-join-detect-start-manually" id="press-start-to-join-detect-start-manually"></a>Method 3: Detect &quot;Start&quot; button press manually:</strong></p>
<ol>
<li> <a href="RewiredEditor.html#settings">(Optional) disable Joystick auto-assignment</a> in the Rewired Editor.</li>
<li> <a href="#assigning-joysticks">Assign all Joysticks</a> to the <a href="Players.html#system-player">System Player</a> on start so we can detect the result of <a href="Actions.html">Actions</a> on Start and whenever one is connected.</li>
<li> <a href="#get-input">Check for the value of the &quot;Start&quot; Action</a> you've created and assigned to the Start button or other appropriate button in your <a href="ControllerMaps.html">Joystick Maps</a>.</li>
<li><a href="#get-contributing-input-sources">Get a list of contributing input sources for the &quot;Start&quot; Action</a> and get the target <a href="Controllers.html#joysticks">Joystick</a> from <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_InputActionSourceData_controller.htm">InputActionSourceData.controller</a>.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Player_ControllerHelper_AddController.htm" target="_blank" rel="nofollow">Assign that Joystick to Player 1 and deassign it from System</a>.</li>
</ol>
</ol>
<p>The following code shows an example implementation of Method 3:</p>
<pre class="code"><span class="comment">/* Prerequisites:<br /> * 1. Create &quot;JoinGame&quot; Action.<br /> * 2. Create Map Categories &quot;Assignment&quot; and &quot;UI&quot;.<br /> * 3. Create Joystick and Keyboard Maps in the &quot;Assignment&quot; category that map &quot;JoinGame&quot;<br /> * to some buttons/keys such as &quot;Start&quot; on in the Gamepad Template and &quot;Space&quot;<br /> * and/or &quot;Enter&quot; in the Keyboard Map.<br /> * 4. Create Joystick and Keyboard Maps in the &quot;UI&quot; category for controlling the UI.<br /> * 5. Assign the &quot;Assignment&quot; maps to each Player (assign the Keyboard Map to only 1 Player unless you've<br /> * created multiple in different layouts for each Player to use). Ensure they are set to be enabled on start.
* 6. Assign the &quot;UI&quot; maps to each Player setting them to be disabled on start.<br /> * 7. Leave joystick auto-assignment enabled.<br /> */</span>
using UnityEngine;
using System.Collections.Generic;
namespace Rewired.Demos {
using Rewired;
public class PressStartToJoinPlayerSelector2 : MonoBehaviour {
public int maxPlayers = 4;
private int rewiredPlayerIdCounter = 0;
<span class="comment">// Track which Joysticks we've seen before in this session so we can tell new joysticks vs ones that have already been assigned to a Player</span>
private List&lt;int&gt;<int> assignedJoysticks;
void Awake() {
assignedJoysticks = new List&lt;int&gt;<int>();
<span class="comment">// Subscribe to controller connected events</span>
ReInput.ControllerConnectedEvent += OnControllerConnected;
}
void Start() {
<span class="comment">// NOTE: On some platforms/input sources, joysticks are ready at this time, but on others they may not be ready yet.
// Must also check in OnControllerConected event.</span>
<span class="comment">// Assign all Joysticks to the System Player initially removing assignment from other Players.</span>
AssignAllJoysticksToSystemPlayer(true);
}
void OnControllerConnected(ControllerStatusChangedEventArgs args) {
if(args.controllerType != ControllerType.Joystick) return;
<span class="comment">// Check if this Joystick has already been assigned. If so, just let Auto-Assign do its job.</span>
if(assignedJoysticks.Contains(args.controllerId)) return;
<span class="comment">// Joystick hasn't ever been assigned before. Make sure it's assigned to the System Player until it's been explicitly assigned</span>
ReInput.players.GetSystemPlayer().controllers.AddController(
args.controllerType,
args.controllerId,
true <span class="comment">// remove any auto-assignments that might have happened</span>
);
}
void AssignAllJoysticksToSystemPlayer(bool removeFromOtherPlayers) {
foreach(var j in ReInput.controllers.Joysticks) {
ReInput.players.GetSystemPlayer().controllers.AddController(j, removeFromOtherPlayers);
}
}
void Update() {
<span class="comment">// Watch for JoinGame action in System Player</span>
if(ReInput.players.GetSystemPlayer().GetButtonDown("JoinGame")) {
AssignNextPlayer();
}
}
void AssignNextPlayer() {
if(rewiredPlayerIdCounter >= maxPlayers) {
Debug.Log("Max player limit already reached!");
return;
}
<span class="comment">// Get the next Rewired Player Id</span>
int rewiredPlayerId = GetNextGamePlayerId();
<span class="comment">// Get the Rewired Player</span>
Player rewiredPlayer = ReInput.players.GetPlayer(rewiredPlayerId);
<span class="comment">// Determine which Controller was used to generate the JoinGame Action</span>
Player systemPlayer = ReInput.players.GetSystemPlayer();
var inputSources = systemPlayer.GetCurrentInputSources("JoinGame");
foreach(var source in inputSources) {
if(source.controllerType == ControllerType.Keyboard || source.controllerType == ControllerType.Mouse) { // Assigning keyboard/mouse
<span class="comment">// Assign KB/Mouse to the Player</span>
AssignKeyboardAndMouseToPlayer(rewiredPlayer);
<span class="comment">// Disable KB/Mouse Assignment category in System Player so it doesn't assign through the keyboard/mouse anymore</span>
ReInput.players.GetSystemPlayer().controllers.maps.SetMapsEnabled(false, ControllerType.Keyboard, "Assignment");
ReInput.players.GetSystemPlayer().controllers.maps.SetMapsEnabled(false, ControllerType.Mouse, "Assignment");
break;
} else if(source.controllerType == ControllerType.Joystick) { // assigning a joystick
<span class="comment">// Assign the joystick to the Player. This will also un-assign it from System Player</span>
AssignJoystickToPlayer(rewiredPlayer, source.controller as Joystick);
break;
} else { <span class="comment">// Custom Controller</span>
throw new System.NotImplementedException();
}
}
<span class="comment">// Enable UI map so Player can start controlling the UI</span>
rewiredPlayer.controllers.maps.SetMapsEnabled(true, "UI");
}
private void AssignKeyboardAndMouseToPlayer(Player player) {
<span class="comment">// Assign mouse to Player</span>
player.controllers.hasMouse = true;
<span class="comment">// Load the keyboard and mouse maps into the Player</span>
player.controllers.maps.LoadMap(ControllerType.Keyboard, 0, "UI", "Default", true);
player.controllers.maps.LoadMap(ControllerType.Keyboard, 0, "Default", "Default", true);
player.controllers.maps.LoadMap(ControllerType.Mouse, 0, "Default", "Default", true);
<span class="comment">// Exclude this Player from Joystick auto-assignment because it is the KB/Mouse Player now</span>
player.controllers.excludeFromControllerAutoAssignment = true;
Debug.Log("Assigned Keyboard/Mouse to Player " + player.name);
}
private void AssignJoystickToPlayer(Player player, Joystick joystick) {
<span class="comment">// Assign the joystick to the Player, removing it from System Player</span>
player.controllers.AddController(joystick, true);
<span class="comment">// Mark this joystick as assigned so we don't give it to the System Player again</span>
assignedJoysticks.Add(joystick.id);
Debug.Log("Assigned " + joystick.name + " to Player " + player.name);
}
private int GetNextGamePlayerId() {
return rewiredPlayerIdCounter++;
}
}
}</pre>
<p>&nbsp;</p>
<p> A quicker but less accurate method would be to do step 1-3 above then:<strong><br />
</strong><br />
Loop through each <a href="Controllers.html#joysticks">Joystick</a> in the <a href="Players.html#system-player">System Player</a> and <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Controller_GetLastTimeAnyButtonPressed.htm" target="_blank" rel="nofollow">find out which Joystick was the last to have any button pressed</a> and assign that <a href="Controllers.html#joysticks">Joystick</a> to the <a href="Players.html">Player</a>.<br />
<br />
This isn't perfect since any button could have been pressed on any <a href="Controllers.html#joysticks">Joystick</a> besides the ones assigned to the &quot;Start&quot; action, but in most cases it would probably work fine.<br />
<br />
There are also other functions to get the last active <a href="Controllers.html#joysticks">Joystick</a>, but they won't help you here because you're only concerned with the &quot;Start&quot; button press and not axes, etc.<br />
<br />
<strong><a name="press-start-to-join-poll-button-by-index" id="press-start-to-join-poll-button-by-index"></a>Method 4: Poll a specific button by index on a specific controller:</strong></p>
<p>This method only works if you know your users are going to only be using one specific controller type (such as an Xbox controller on an Xbox system).<br />
</p>
<ol>
<li>Use <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ControllerPollingInfo_elementIdentifierId.htm" target="_blank" rel="nofollow">ReInput.controllers.polling.PollAllControllersForAllButtons</a> to poll for button presses.</li>
<li>Check the returned <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ControllerPollingInfo_elementIdentifierId.htm" target="_blank" rel="nofollow">ControllerPollingInfo.elementIdentifierId </a>or <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ControllerPollingInfo_elementIdentifierName.htm" target="_blank" rel="nofollow">ControllerPollingInfo.elementIdentifierName </a>to determine which button was pressed.
</li>
</ol>
<p><strong><a name="press-start-to-join-controller-template" id="press-start-to-join-controller-template"></a>Method 5: Poll a specific button on a Controller Template:</strong></p>
<p>This method only works for Controllers that support <a href="ControllerTemplates.html">Controller Templates</a>.</p>
<ol>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Player_ControllerHelper_GetControllerTemplates__1.htm" target="_blank">Loop through all Controllers Templates of a particular type</a>.</li>
<li>Check the value of the Start button on the template if it supports one such as gamepad.start.</li>
</ol>
<p>&nbsp;</p>
<hr />
<h3><a name="saving-loading-controller-maps" id="saving-loading-controller-maps"></a>Saving and loading Controller Maps</h3>
<p><a href="UserDataStore.html">UserDataStore</a> is a class designed to help with saving and loading of <a href="ControllerMaps.html">Controller Maps</a>, <a href="InputBehaviors.html">Input Behaviors</a>, calibration settings, and more. Please see <a href="UserDataStore.html">User Data Store</a> for more information.</p>
<p>There are several steps involved in saving and loading <a href="ControllerMaps.html">Controller Maps</a>.</p>
<p><strong>Saving:</strong></p>
<ol>
<li>Get the save data from each <a href="Players.html">Player</a> in XML or JSON format.</li>
<li>Save the data to a storage medium.</li>
</ol>
<p><strong>Loading:</strong></p>
<ol>
<li>Identify the <a href="Controllers.html">Controllers</a> you want to load maps for.</li>
<li>Load the map data in XML or JSON format.</li>
<li>Set the map data in the <a href="Players.html">Player</a>.</li>
</ol>
<p>Rewired includes a basic system for storing the saved data -- <a href="UserDataStore.html">UserDataStore_PlayerPrefs</a> which may not be suitable for everyone. Since every game and platform may have different requirements for data storage, you will probably want to write your own data storage system for your specific needs. You will have to save the data in a format most suitable to your game and platform. Possible options are PlayerPrefs, a database, binary or text files, cloud storage, etc. (<a href="UserDataStore.html">UserDataStore</a> can optionally be extended to support any storage medium.)<br />
</p>
<p>The example mapping demo in Rewired/Examples/ControlRemapping1 includes saving and loading of <a href="ControllerMaps.html">Controller Maps</a>, Axis Calibration Maps, and <a href="InputBehaviors.html">Input Behaviors</a>. See this demo project to learn the process of saving and loading. Note: The demo project uses PlayerPrefs for the data storage medium. This is not ideal, but was done for simplicity and cross-platform compatibility for the example. It should not be difficult to substitute another storage medium suitable to your platform. </p>
<p><strong>Example Code from the ControlRemapping1 (see example in Rewired/Examples/ControlRemapping1 for complete code)</strong></p>
<pre class="code">private void SaveAllMaps() {
<span class="comment">// This example uses PlayerPrefs because its convenient, though not efficient, but you could use any data storage method you like.</span>
IList&lt;Player&gt; allPlayers = ReInput.players.AllPlayers;
for(int i = 0; i &lt; allPlayers.Count; i++) {
Player player = allPlayers[i];
<span class="comment">// Get all savable data from player</span>
PlayerSaveData playerData = player.GetSaveData(true);
<span class="comment">// Save Input Behaviors</span>
foreach(InputBehavior behavior in playerData.inputBehaviors) {
string key = GetInputBehaviorPlayerPrefsKey(player, behavior);
PlayerPrefs.SetString(key, behavior.ToXmlString()); <span class="comment">// save the behavior to player prefs in XML format</span>
}
<span class="comment">// Save controller maps</span>
foreach(ControllerMapSaveData saveData in playerData.AllControllerMapSaveData) {
string key = GetControllerMapPlayerPrefsKey(player, saveData);
PlayerPrefs.SetString(key, saveData.map.ToXmlString()); <span class="comment">// save the map to player prefs in XML format</span>
}
}
<span class="comment">// Save joystick calibration maps</span>
foreach(Joystick joystick in ReInput.controllers.Joysticks) {
JoystickCalibrationMapSaveData saveData = joystick.GetCalibrationMapSaveData();
string key = GetJoystickCalibrationMapPlayerPrefsKey(saveData);
PlayerPrefs.SetString(key, saveData.map.ToXmlString()); <span class="comment">// save the map to player prefs in XML format</span>
}
<span class="comment">// Save changes to PlayerPrefs</span>
PlayerPrefs.Save();
}
private void LoadAllMaps() {
<span class="comment">// This example uses PlayerPrefs because its convenient, though not efficient, but you could use any data storage method you like.</span>
IList&lt;Player&gt; allPlayers = ReInput.players.AllPlayers;
for(int i = 0; i &lt; allPlayers.Count; i++) {
Player player = allPlayers[i];
<span class="comment">// Load Input Behaviors - all players have an instance of each input behavior so it can be modified</span>
IList&lt;InputBehavior&gt; behaviors = ReInput.mapping.GetInputBehaviors(player.id); <span class="comment">// get all behaviors from player</span>
for(int j = 0; j &lt; behaviors.Count; j++) {
string xml = GetInputBehaviorXml(player, behaviors[j].id); <span class="comment">// try to the behavior for this id</span>
if(xml == null || xml == string.Empty) continue; <span class="comment">// no data found for this behavior</span>
behaviors[j].ImportXmlString(xml); <span class="comment">// import the data into the behavior</span>
}
<span class="comment">// Load the maps first and make sure we have them to load before clearing</span>
<span class="comment">// Load Keyboard Maps</span>
List&lt;string&gt; keyboardMaps = GetAllControllerMapsXml(player, true, ControllerType.Keyboard, ReInput.controllers.Keyboard);
<span class="comment">// Load Mouse Maps</span>
List&lt;string&gt; mouseMaps = GetAllControllerMapsXml(player, true, ControllerType.Mouse, ReInput.controllers.Mouse); <span class="comment">// load mouse controller maps</span>
<span class="comment">// Load Joystick Maps</span>
bool foundJoystickMaps = false;
List&lt;List&lt;string&gt;&gt; joystickMaps = new List&lt;List&lt;string&gt;&gt;();
foreach(Joystick joystick in player.controllers.Joysticks) {
List&lt;string&gt; maps = GetAllControllerMapsXml(player, true, ControllerType.Joystick, joystick);
joystickMaps.Add(maps);
if(maps.Count &gt; 0) foundJoystickMaps = true;
}
<span class="comment">// Now add the maps to the controller</span>
<span class="comment">// Keyboard maps</span>
if(keyboardMaps.Count &gt; 0) player.controllers.maps.ClearMaps(ControllerType.Keyboard, true); <span class="comment">// clear only user-assignable maps, but only if we found something to load. Don't _really_ have to clear the maps as adding ones in the same cat/layout will just replace, but let's clear anyway.</span>
player.controllers.maps.AddMapsFromXml(ControllerType.Keyboard, 0, keyboardMaps); <span class="comment">// add the maps to the player</span>
<span class="comment">// Joystick maps</span>
if(foundJoystickMaps) player.controllers.maps.ClearMaps(ControllerType.Joystick, true); <span class="comment">// clear only user-assignable maps, but only if we found something to load. Don't _really_ have to clear the maps as adding ones in the same cat/layout will just replace, but let's clear anyway.</span>
int count = 0;
foreach(Joystick joystick in player.controllers.Joysticks) {
player.controllers.maps.AddMapsFromXml(ControllerType.Joystick, joystick.id, joystickMaps[count]); <span class="comment">// add joystick controller maps to player</span>
count++;
}
<span class="comment">// Mouse Maps</span>
if(mouseMaps.Count &gt; 0) player.controllers.maps.ClearMaps(ControllerType.Mouse, true); <span class="comment">// clear only user-assignable maps, but only if we found something to load. Don't _really_ have to clear the maps as adding ones in the same cat/layout will just replace, but let's clear anyway.</span>
player.controllers.maps.AddMapsFromXml(ControllerType.Mouse, 0, mouseMaps); <span class="comment">// add the maps to the player</span>
}
<span class="comment">// Load joystick calibration maps</span>
foreach(Joystick joystick in ReInput.controllers.Joysticks) {
joystick.ImportCalibrationMapFromXmlString(GetJoystickCalibrationMapXml(joystick)); <span class="comment">// load joystick calibration map if any</span>
}
}</pre>
<p><strong>Loading the Default Controller Maps:</strong></p>
<p>Default <a href="ControllerMaps.html">Controller Maps</a> are stored in the Rewired Input Manager. You can load the defaults for a <a href="Players.html">Player</a> by using these methods:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Player_ControllerHelper_MapHelper_LoadDefaultMaps.htm">player.controllers.maps.LoadDefaultMaps</a> - Loads all default <a href="ControllerMaps.html">Controller Maps</a> from the Rewired Input Manager for all currently-connected devices. Replaces any existing <a href="ControllerMaps.html">Controller Maps</a> already existing in <a href="Players.html">Player</a>.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_LoadMap.htm">player.controllers.maps.LoadMap</a> - Loads a single <a href="ControllerMaps.html">Controller Map</a> from the Rewired Input Manager.</li>
</ul>
<p>&nbsp;</p>
<p><strong>Useful API Reference:</strong></p>
<p><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Player_GetSaveData.htm">Player.GetSaveData</a> - Get all save data from the player at once. This includes <a href="ControllerMaps.html"> Controller Map</a> data.</p>
<p><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Player_ControllerHelper_MapHelper.htm">player.controllers.maps</a> - Methods to get, set, and work with <a href="ControllerMaps.html"> Controller Maps</a> in <a href="Players.html">Player</a>.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="saving-loading-calibration-maps" id="saving-loading-calibration-maps"></a>Saving and loading Calibration Maps</h3>
<p><a href="UserDataStore.html">UserDataStore</a> is a class designed to help with saving and loading of <a href="ControllerMaps.html"> Controller Maps</a>, <a href="InputBehaviors.html">Input Behaviors</a>, calibration settings, and more. Please see <a href="UserDataStore.html">User Data Store</a> for more information.</p>
<p>The process for saving and loading calibration maps is very similar to <a href="#saving-loading-controller-maps">Saving and loading Controller Maps</a>, except instead of getting the maps from the <a href="Players.html">Player</a>, you must get the Calibration Map data from the <a href="Controllers.html">Controllers</a> themselves.</p>
<p><strong>Example Code from the ControlRemapping1 (see example in Rewired/Examples/ControlRemapping1 for complete code)</strong></p>
<pre class="code">private void SaveAllMaps() {
<span class="comment">// ... Removed controller map saving code</span>
<span class="comment">// Save joystick calibration maps</span>
foreach(Joystick joystick in ReInput.controllers.Joysticks) {
JoystickCalibrationMapSaveData saveData = joystick.GetCalibrationMapSaveData();
string key = GetJoystickCalibrationMapPlayerPrefsKey(saveData);
PlayerPrefs.SetString(key, saveData.map.ToXmlString()); <span class="comment">// save the map to player prefs in XML format</span>
}
<span class="comment">// Save changes to PlayerPrefs</span>
PlayerPrefs.Save();
}
private void LoadAllMaps() {
<span class="comment">// ... Removed controller map loading code</span>
<span class="comment">// Load joystick calibration maps</span>
foreach(Joystick joystick in ReInput.controllers.Joysticks) {
joystick.ImportCalibrationMapFromXmlString(GetJoystickCalibrationMapXml(joystick)); <span class="comment">// load joystick calibration map if any</span>
}
} </pre>
<p><strong>Useful API Reference:</strong></p>
<p><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Player_ControllerHelper_MapHelper.htm">player.controllers.maps</a> - Methods to get, set, and work with <a href="ControllerMaps.html">Controller Maps</a> in <a href="Players.html">Player</a>.</p>
<p><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ControllerWithAxes_calibrationMap.htm">Joystick.calibrationMap</a> - Get the Calibration Map from the <a href="Controllers.html">Controller</a>.</p>
<p><span class="code"><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Joystick_GetCalibrationMapSaveData.htm">Joystick.GetCalibrationMapSaveData</a></span> - Get the Calibration Map save data.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="modifying-input-behaviors-during-runtime" id="modifying-input-behaviors-during-runtime"></a>Modifying Input Behaviors during runtime</h3>
<p>Get the <a href="InputBehaviors.html">Input Behavior</a> you wish to modify from the <a href="Players.html">Player</a>.</p>
<p><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Player_ControllerHelper_MapHelper_InputBehaviors.htm">Player.controllers.maps.InputBehaviors</a> - Gets a list of all <a href="InputBehaviors.html">InputBehaviors</a> in this Player.<br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Player_ControllerHelper_MapHelper_GetInputBehavior.htm">Player.controllers.maps.GetInputBehavior</a> - Gets a specific <a href="InputBehaviors.html">InputBehavior</a>.</p>
<p>Once you have the <a href="InputBehaviors.html">Input Behavior</a>, modify any property you wish.</p>
<p><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_InputBehavior.htm">API Reference - InputBehavior</a></p>
<p>You can save <a href="InputBehaviors.html">Input Behaviors</a> to XML or JSON so your runtime changes can be loaded in another game session. The example mapping demo in Rewired/Examples/ControlRemapping1 includes saving and loading of <a href="ControllerMaps.html">Controller Maps</a>, Axis Calibration Maps, and <a href="InputBehaviors.html">Input Behaviors</a>. See the example for information on how to save and load <a href="InputBehaviors.html">Input Behaviors</a>.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="on-screen-touch-controllers" id="on-screen-touch-controllers"></a><a name="touch-controls" id="on-screen-touch-controllers2"></a>Creating on-screen touch controls</h3>
<p>Rewired includes a set of <a href="TouchControls.html">touch controls</a> which you can use directly in your game. For special needs not covered by the included touch controls, you can create your own by using <a href="CustomControllers.html">Custom Controllers</a> to map touch input to Actions.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="controller-mapping-screen" id="controller-mapping-screen"></a>Creating a controller mapping screen</h3>
<p>Rewired now includes <a href="ControlMapper.html">Control Mapper</a>, a customizable UI control mapping system built with Unity UI that should fit the needs of many games. Please see <a href="ControlMapper.html">Control Mapper</a> for more information.</p>
<p><strong>Creating a mapping screen from scratch</strong></p>
<p> To get you started, for an exhaustive example, see the example mapping screen in <a href="Examples.html#control-remapping-1">Rewired/Examples/ControlRemapping1</a>. The example uses Unity's legacy GUI system. For a much simpler but less complete example, see <a href="Examples.html#simple-control-remapping">Rewired/Examples/SimpleControlRemapping</a>.</p>
<p>Every game's needs are different with regards to user mapping screens. The ControlRemapping1 example was built for a fairly complex game with a number of players and various game modes and supports saving and loading <a href="ControllerMaps.html">Controller Maps</a>, <a href="Controllers.html#joysticks">Joystick</a> assignment, element remapping, calibration, conflict checking, and more. You should be able to learn what you need to from the example project to create your own mapping screen.</p>
<p>Before beginning, it is very important to understand the Controller Map structure and how input is processed in a Player. Please read <a href="ControllerMaps.html">Controller Maps</a> and also <a href="ControllerMaps.html#how-input-is-processed">Controller Maps - How Input is Processed in Controller Maps</a> for more information.</p>
<p>Just as a brief summary, the basic process for changing an element's mapping goes like this:</p>
<ol>
<li> <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_ReInput_PlayerHelper_GetPlayer.htm">Get the Player</a> for which you are changing element mappings.</li>
<li>Get the <a href="ControllerMaps.html">ControllerMap</a> you want to modify from the <a href="Players.html">Player</a>.<br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Player_ControllerHelper_MapHelper.htm">Various functions here</a> can help in finding it. For example:<br />
<a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Overload_Rewired_Player_ControllerHelper_MapHelper_GetMap.htm">player.controllers.maps.GetMap</a></li>
<li>Listen for controller input using <a href="InputMapper.html">Input Mapper</a>.</li>
<li><a href="InputMapper.html#conflicts">Handle assignment conflicts</a>.</li>
</ol>
<p>Examples:</p>
<ul>
<li><a href="Examples.html#simple-control-remapping">Simple Control Remapping</a></li>
<li><a href="Examples.html#simple-combined-keyboard-mouse-remapping">Combined Keyboard Mouse Remapping</a></li>
<li><a href="Examples.html#control-remapping-1">Control Remapping 1</a></li>
<li><a href="ControlMapper.html">Control Mapper (see source code)</a> </li>
</ul>
<p><strong>IMPORTANT:</strong></p>
<p><em>I do not provide support for making your own control remapping system.</em></p>
<ul>
<li> I have provided 4 working examples for those expert programmers to use to learn the API so they can make their own remapping systems.</li>
<li>I have provided a complete, drop-in UI system, <a href="ControlMapper.html">Control Mapper</a>, for those that can't write their own system or don't want to spend the time reading the examples to learn how to do so.</li>
</li>
</ul>
<p>If looking through the examples to learn is too difficult, use <a href="ControlMapper.html">Control Mapper</a>.</p>
<p>Do not contact support asking for help writing your remapping system, asking how to do each step of the process, asking for tutorials or code examples, or sending code asking why it doesn't work. All the answers to all questions related to this topic are in the examples provided.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="conflict-checking" id="conflict-checking"></a>Conflict Checking</h3>
<p>When using <a href="ControlMapper.html">Control Mapper</a>, <a href="InputMapper.html">Input Mapper</a>, or when manually creating a control remapping system using the low-level API, before a controller element is bound, a conflict check can be performed to determine if any existing bindings exist that would conflict with the new binding so you can determine what action to take to resolve the conflict(s).</p>
<p>Rewired's conflict checking system tries to prevent the user from cross-assigning his controls. For example, if the user tries to assign the key A to &quot;Fire&quot; after it has already been assigned to &quot;Jump&quot;, a warning will be displayed asking the user whether they would like to replace the assignment or (optionally) add the new conflicting assignment anyway.</p>
<p>The Rewired Input Manager has many options for controlling conflict checking. These are handled on a Map Category basis. You are able to set which Map Categories perform conflict checking against other Map Categories. This conflict checking is configurable independently each way, so if you want one Map Category to conflict check against another but not vice versa, this is possible. Additionally, this allows you to have categories such as &quot;Common&quot;, &quot;Infantry Mode&quot;, &quot;Tank Mode&quot;, &quot;Airplane Mode&quot; and have all these maps configurable by the user without having conflict checking between mutually-exclusive Map Categories such as &quot;Tank Mode&quot; and &quot;Infantry Mode&quot; while all still conflict checking against &quot;Common&quot; and vice versa. See <a href="https://guavaman.com/projects/rewired/docs/RewiredEditor.html#MapCategories">Rewired Editor - Map Categories</a> for more information.</p>
<p><strong>Protected controls</strong></p>
<p>You may want to have certain controls protected from re-assignment. One example of this might be the ESC key if you use that for some important system control and you don't want the user removing this assignment by trying to assign ESC to another Action. In Rewired, protection of controls is handled on the Map Category level. To protect a set of System controls from ever being re-assigned, uncheck the <a href="https://guavaman.com/projects/rewired/docs/RewiredEditor.html#MapCategories">&quot;User Assignable&quot; checkbox in the Map Category</a> that contains the Action in the Rewired Input Manager.</p>
<ul>
<li>Map Category -&gt; User Assignable</li>
</ul>
<p>&nbsp;</p>
<hr />
<h3><a name="new-controller-definitions" id="new-controller-definitions"></a>Creating new controller definitions</h3>
<p><em>This is an advanced topic. Creating definitions requires a number of tools to help identify the elements and requires thorough testing on several platforms if you desire cross-platform compatibility. To make this process easier, if you have a controller you want to support, please let me know via the support form on the website. I will do my best to get ahold of the controller and add definitions for it. If I cannot, you can arrange to mail the controller to me and I will add definitions for it and then mail it back to you.</em></p>
<p><a href="https://www.youtube.com/watch?v=VkYVkRnjgjk" target="_blank">A video tutorial is available on YouTube here.</a></p>
<p><strong>IMPORTANT:</strong> Not all controllers are suitable for automatic recognition. Creating definitions for some controllers can cause many problems. <a href="FAQ.html#addding-controller-definitions">Read this first before making a new controller definition</a>.</p>
<p>You can create your own controller definitions if you want to support a specific controller without requiring the user manually map their controller elements. However there are several things you need to be aware of if you want to modify the list of supported controllers:</p>
<ol>
<li>You should copy the ControllerDataFiles object in Rewired/Internal/Data/Controllers to another location (preferably outside the Internal folder) and modify the copy. <em>NEVER modify the original ControllerDataFiles, otherwise when you upgrade Rewired, your ControllerDataFiles will be overwritten and your changes lost.</em></li>
<li>You will need to link your Rewired Input Manager to the new ControllerDataFiles object. Click your Rewired Input Manager in the scene hierarchy and drag-and-drop your copy of ControllerDataFiles into the Data Files field in the inspector. This will instruct Rewired to use your modified ControllerDataFiles instead of the default original.</li>
<li><em>NEVER modify any of the default Hardware Joystick Map or Hardware Joystick Template Map files.</em> If you do, the next time you upgrade Rewired, your changes will be overwritten. Instead, make a copy of any map you wish to modify, move it to another location (preferably outside the Internal folder), also copy the ControllerDataFiles object to another location, then link up the reference to the new Hardware Joystick Map or Hardware Joystick Template map in your ControllerDataFiles object.</li>
</ol>
<p><strong>Now that you know the rules, here are the steps to creating a new controller:</strong></p>
<ol>
<li>Copy ControllerDataFiles to a new location.</li>
<li>Create a new HardwareJoystickMap object from the menu: Window -&gt; Rewired -&gt; Create -&gt; Assets -&gt; Hardware Joystick Map.</li>
<li>Move the Hardware Joystick Map to a suitable location.</li>
<li>Click your copy of ControllerDataFiles, then in the inspector, modify the Hardware Joystick Maps array to increase its size.</li>
<li>Drag and drop your new Hardware Joystick Map into the new element in the array.</li>
<li>Now, to edit your new Hardware Joystick Map, click its file and then click &quot;Launch Hardware Joystick Map Editor&quot; in the inspector.</li>
<li>Edit the Hardware Joystick Map. The process is as follows:
<ul>
<li>Create Element Identifiers for each of the controller's physical elements. An element can be designated as an Axis or a Button.</li>
<li>Select a platform you wish to map such as Raw/Direct Input.</li>
<li>On the Matching Criteria tab, fill out the information used to identify the controller. You can get this information by using the tool included for the platform you're editing. See Step 8 below.</li>
<li>Create axes and buttons and map them to the platform's input sources. There are various options to help you deal with axes that behave in non-standard ways.</li>
<li>Hats should be mapped to buttons, one for each of the four directions.</li>
</ul>
</li>
<li>To identify the joystick elements on a particular platform, you may use the tools in the Rewired/DevTools folder. Open the JoystickElementIdentifier scene. Change the configuration in the Rewired Input Manager if you need to make a definition for a different input source than the default. Press play to see a readout of joystick elements as you move axes and press buttons on the device. You may split the game window and edit your hardware map while the game is running so you can see the readout of the elements.</li>
<li>Link your new ControllerDataFiles to your Input Manager in the scene so it will recognize the new joysticks.</li>
</ol>
<p><strong>The Hardware Joystick Map Editor window</strong></p>
<p><img src="files/images/hardwarejoystickmapeditor_settings.png" alt="Hardware Joystick Map Editor" /></p>
<hr />
<h3><a name="new-controller-templates" id="new-controller-templates"></a>Creating new controller templates</h3>
<p><em>This is an advanced topic. Creating definitions requires a number of tools to help identify the elements and requires thorough testing on several platforms if you desire cross-platform compatibility. To make this process easier, if you have a controller you want to support, please let me know via the support form on the website. I will do my best to get ahold of the controller and add definitions for it. If I cannot, you can arrange to mail the controller to me and I will add definitions for it and then mail it back to you.</em></p>
<p>See <a href="#new-controller-definitions">Creating new controller definitions</a> for precautions on working with ControllerDataFiles and Hardware Joystick Maps as the same rules apply here.</p>
<ol>
<li>Create a new HardwareJoystickTemplateMap object from the menu: Window -&gt; Rewired -&gt; Create -&gt; Assets -&gt; Hardware Joystick Template Map.</li>
<li>Move the Hardware Joystick Template Map to a suitable location.</li>
<li>Click your copy of ControllerDataFiles, then in the inspector, modify the Joystick Templates array to increase its size.</li>
<li>Drag and drop your new Hardware Joystick Template Map into the new element in the array.</li>
<li>Now, to edit your new Hardware Joystick Template Map, click its file and then click &quot;Launch Hardware Joystick Template Map Editor&quot; in the inspector.</li>
<li>Edit the hardware joystick template map by filling out the information. You will need to create a list of Element Identifiers for this template, add joysticks for each joystick the template supports, and create the maps for each joystick.</li>
<li>Add a reference to the new Controller Template to your copy of Controller Data Files under the Templates section.</li>
<li>Generate scripts for your templates. Click on your copy of Controller Data Files and in the inspector click &quot;Generate Controller Templates Script&quot; and save the file somewhere outside the Rewired folder.</li>
<li>Enable the use of your templates by enabling user templates in the Global Options window: Window -&gt; Rewired -&gt; Global Options -&gt; Enable User-Defined Controller Templates.</li>
</ol>
<p>&nbsp;</p>
<hr />
<h3><a name="add-controller-to-existing-controller-template" id="new-controller-templates2"></a>Adding a controller to an existing controller template</h3>
<p><em>This is an advanced topic. Creating definitions requires a number of tools to help identify the elements and requires thorough testing on several platforms if you desire cross-platform compatibility. To make this process easier, if you have a controller you want to support, please let me know via the support form on the website. I will do my best to get ahold of the controller and add definitions for it. If I cannot, you can arrange to mail the controller to me and I will add definitions for it and then mail it back to you.</em></p>
<p>See <a href="#new-controller-definitions">Creating new controller definitions</a> for precautions on working with ControllerDataFiles and Hardware Joystick Maps as the same rules apply here.</p>
<p><a href="https://www.youtube.com/watch?v=VkYVkRnjgjk" target="_blank">A video tutorial is available on YouTube here.</a></p>
<p>You can add a new controller definition to an existing template. Be sure the new controller has similar elements and a similar layout. The steps are as follows:</p>
<ol>
<li>First select the Hardware Joystick Map Template object from the Project view.</li>
<li>Click the &quot;Launch Hardware Joystick Template Map Editor&quot; button in the inspector.</li>
<li>In the window, select the &quot;Joysticks&quot; tab.</li>
<li>Add a new joystick which will appear at the bottom of the list.</li>
<li>Give this joystick a name. This is only used for identification purposes in this editor.</li>
<li>You will need to get the GUID of the joystick you're adding from the Hardware Joystick Map file. Open the Hardware Joystick Map editor for the joystick you're adding, then copythe GUID from the &quot;Settings&quot; tab and paste it in the &quot;Joystick Guid&quot; field of the new joystick in the template editor.</li>
<li>You will also need to get the Unity file GUID of the Hardware Joystick Map. This is different from the above GUID. You can obtain this file GUID enabling &quot;Visible Meta Files&quot; in Edit -&gt; Project Settings -&gt; Editor in the application menu, then navigating to the folder with the Hardware Joystick Map and opening the .meta file associated with the asset. The GUID should be clearly visible. Copy this GUID and paste it into the &quot;File Guid&quot; field of your new joystick in the template editor.</li>
<li>On the &quot;Maps&quot; tab of the template editor, select your new joystick from the dropdown at the top.</li>
<li>Click &quot;Add Entry&quot; to add a new element.</li>
<li>You will be mapping each joystick element to a template element. The elements are listed by name.</li>
<li>Add as many elements as there are Element Identifiers in your joystick.</li>
</ol>
<p>&nbsp;</p>
<hr />
<h3><a name="excluding-controller-definitions" id="excluding-controller-definitions"></a>Excluding controller definitions</h3>
<p>See <a href="#new-controller-definitions">Creating new controller definitions</a> for precautions on working with ControllerDataFiles and Hardware Joystick Maps as the same rules apply here.</p>
<p>If there is a particular controller that is included with Rewired that you don't want to support for some reason, you must do the following:</p>
<ol>
<li>Copy ControllerDataFiles to a new location.</li>
<li>Click your copy of ControllerDataFiles, then in the inspector, remove the controller(s) you don't want to support from the Hardware Joystick Maps array.</li>
<li>Link your new ControllerDataFiles to your Input Manager in the scene so it will use the new joystick list.</li>
</ol>
<p>&nbsp;</p>
<hr />
<h3><a name="identifying-recognized-controllers" id="identifying-recognized-controllers"></a>Identifying recognized Joysticks</h3>
<p>
If you need to identify a <a href="Controllers.html#joysticks">Joystick</a> for some reason (you're building <a href="#display-glyph-for-action">a controller element glyph table</a> for example), you can determine the identity of a <a href="Controllers.html#joysticks">Joystick</a> by using the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Controller_hardwareTypeGuid.htm">joystick.hardwareTypeGuid property</a>. This will return the unique GUID of the <a href="Controllers.html#joysticks">Joystick</a> type. (Note: This is a Rewired-generated GUID, not from the hardware.) This GUID can be found in each HardwareJoystickMap on the Settings page. HardwareJoystickMaps can be found in the Assets/Rewired/Internal/Data/Controllers/HardwareMaps/Joysticks/ folder in your project.</p>
<p>(To save time, you can <a href="https://guavaman.com/rewired/files/docs/RewiredControllersCSV.zip">download a CSV file of the current controllers here</a>.)</p>
<p>If a <a href="Controllers.html#joysticks">Joystick</a> is not a recognized controller, it will always return Guid.Empty (all zeros).</p>
<p>Be sure to note the <a href="ControllerMaps.html#xinput-devices-windows">special cases for certain controllers on some platfoms/input sources as noted here</a> as this affects what a controller is identified as.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="identifying-joysticks-windows-fallback-or-webplayer" id="identifying-joysticks-windows-fallback-or-webplayer"></a>Identifying controllers on Windows fallback or Windows Webplayer platforms</h3>
<p><strong>Update:</strong> Unity fixed this issue on Windows in Unity 4.6.3p1 and an early version of Unity 5.x. You can check if the current version of Unity includes the fix by checking the value of <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_ReInput_unityJoystickIdentificationRequired.htm">ReInput.unityJoystickIdentificationRequired</a>. If true, you should allow your players to manually identify controllers using the methods described below.</p>
<p><strong>Update 2:</strong> Windows UWP in Unity fallback mode also has this same issue.</p>
<p>Because of limitations of Unity's input system, you need to take special measures on these platforms for controllers on Windows Standalone (only if you're <strong>not</strong> using native input -- Raw Input, Direct Input, or XInput -- native input does not have this problem) and Windows Webplayer (native input is not available in Webplayer). Note: This procedure is not required for OSX or other platforms.</p>
<p>Unity's input system has a major problem that makes it impossible to accurately identify which joystick id belongs to which physical controller in Windows. To solve this issue, at game start and at any point a controller is either connected or disconnected, you should ask the user to manually identify each controller one-by-one by pressing a button on the controller that matches the name displayed on-screen.</p>
<p>Rewired provides several functions to facilitate joystick identification:</p>
<p><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_ReInput_ControllerHelper_GetUnityJoystickIdFromAnyButtonOrAxisPress.htm">GetUnityJoystickIdFromAnyButtonOrAxisPress</a> - Returns the 0 based id of the Unity joystick whose button or axis was pressed. -1 if no button or axis was pressed on any joystick. Use this to identify controllers when using Unity's input system. This has no effect if Unity Input is not handling input on the current platform. </p>
<p><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_ReInput_ControllerHelper_GetUnityJoystickIdFromAnyButtonPress.htm">GetUnityJoystickIdFromAnyButtonPress</a> - Returns the 0 based id of the Unity joystick whose button was pressed. -1 if no button was pressed on any joystick. Use this to identify controllers when using Unity's input system. This has no effect if Unity Input is not handling input on the current platform. </p>
<p><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_ReInput_ControllerHelper_SetUnityJoystickIdFromAnyButtonOrAxisPress.htm">ReInput.controllers.SetUnityJoystickIdFromAnyButtonOrAxisPress</a> - Sets a Unity joystick as the input source of a <a href="Controllers.html#joysticks">Joystick</a>. The first Unity joystick that returns a button or axis press will be assigned to the <a href="Controllers.html#joysticks">Joystick</a>. While no buttons or axes are pressed, this will return False. When a press is detected, it will return True and assign the joystick id. </p>
<p><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_ReInput_ControllerHelper_SetUnityJoystickIdFromAnyButtonPress.htm">ReInput.controllers.SetUnityJoystickIdFromAnyButtonPress</a> - Sets a Unity joystick as the input source of a <a href="Controllers.html#joysticks">Joystick</a>. The first Unity joystick that returns a button press will be assigned to the <a href="Controllers.html#joysticks">Joystick</a>. While no buttons are pressed, this will return False. When a button press is detected, it will return True and assign the joystick id. </p>
<p><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_ReInput_ControllerHelper_SetUnityJoystickId.htm">ReInput.controllers.SetUnityJoystickId</a> - Sets a Unity joystick as the input source of a <a href="Controllers.html#joysticks">Joystick</a>. Use this to remap a <a href="Controllers.html#joysticks">Joystick</a> to its source when reconnected on platforms that use Unity Input. This has no effect if Unity Input is not handling input on the current platform.</p>
<p>An example is included in Rewired/Examples/FallbackJoystickIdentification which you can look at to see how this is done.</p>
<p>The basic idea is this:</p>
<ol>
<li>At game start, pop up a GUI asking the user to press a button on each named controller.</li>
<li>When the user presses the button, set the joystick id on the <a href="Controllers.html#joysticks">Joystick</a> so Rewired can identify which physical controller it is.</li>
<li>Repeat the above steps for each controller attached to the system.</li>
<li>Any time a controller is connected or disconnected, repeat the whole identification process for every controller.</li>
</ol>
<p>Once the controllers are properly identified, you can use Rewired as usual to receive input, remap controllers, etc. and everything will function properly.</p>
<p>Note: If the user has more than one controller with identical names, there is no way to distinguish between the various controllers for identification. The order that the user identifies the controllers may change <a href="Controllers.html#joysticks">Joystick</a> to <a href="Players.html">Player</a> assignments. There is nothing you can do to prevent this. If this happens, the user will have to reassign the <a href="Controllers.html#joysticks">Joysticks</a> to <a href="Players.html">players</a> manually using a controller mapping screen. See <a href="#controller-mapping-screen">Creating a controller mapping screen</a> for more information.</p>
<p><strong>FallbackJoystickIdentificationDemo.cs from Rewired/Examples/FallbackJoystickIdentification</strong></p>
<pre class="code">
<span class="comment">// This example shows how to have the user manually identify joysticks by name to assit with a Unity<br />// bug where joysticks cannot be associated with a Unity joystick ID without manual intervention when<br />// using Unity as the input source (as opposed to native input).
// NOTE: This only affects the Windows Standalone and Windows Webplayer platforms and was patched by Unity in 4.6.3p1,<br />// so this is no longer required in Unity 4.x versions after 4.6.3p1.<br />// This was also fixed in an early version of Unity 5.x, but not in 5.0.
</span>
using UnityEngine;
using System.Collections.Generic;
<br />namespace Rewired.Demos {
[AddComponentMenu("")]
public class FallbackJoystickIdentificationDemo : MonoBehaviour {
<span class="comment">// Consts</span>
private const float windowWidth = 250.0f;
private const float windowHeight = 250.0f;
private const float inputDelay = 1.0f;
<span class="comment">// Working vars</span>
private bool identifyRequired;
private Queue<Joystick> joysticksToIdentify;
private float nextInputAllowedTime;
private GUIStyle style;
private void Awake() {
if(!ReInput.unityJoystickIdentificationRequired) return; <span class="comment">// this platform does not require manual joystick identificaion</span>
<span class="comment">// Subscribe to device change events</span>
ReInput.ControllerConnectedEvent += JoystickConnected;
ReInput.ControllerDisconnectedEvent += JoystickDisconnected; <span class="comment">// this event is called after joystick is fully disconnected and removed from lists</span>
IdentifyAllJoysticks();
}
private void JoystickConnected(ControllerStatusChangedEventArgs args) {
<span class="comment">// Identify all joysticks on connect or disconnect because ids are not reliable in Unity</span>
IdentifyAllJoysticks();
}
private void JoystickDisconnected(ControllerStatusChangedEventArgs args) {
<span class="comment">// Identify all joysticks on connect or disconnect because ids are not reliable in Unity</span>
IdentifyAllJoysticks();
}
public void IdentifyAllJoysticks() {
<span class="comment">// Reset each time in case user changes joysticks while dialog is open</span>
Reset();
<span class="comment">// Check if there are any joysticks</span>
if(ReInput.controllers.joystickCount == 0) return; <span class="comment">// no joysticks, nothing to do</span>
<span class="comment">// Get current Joysticks</span>
Joystick[] joysticks = ReInput.controllers.GetJoysticks();
if(joysticks == null) return;
<span class="comment">// Set flag to enable identification mode</span>
identifyRequired = true;
<span class="comment">// Create a queue out of the joysticks array</span>
joysticksToIdentify = new Queue<Joystick>(joysticks);
<span class="comment">// Set the time for accepting input again</span>
SetInputDelay();
}
private void SetInputDelay() {
<span class="comment">// Prevent user input for a period of time after each identification to handle button hold problem</span>
nextInputAllowedTime = Time.time + inputDelay;
}
private void OnGUI() {
if(!identifyRequired) return;
if(joysticksToIdentify == null || joysticksToIdentify.Count == 0) {
Reset();
return;
}
<span class="comment">// Draw dialog window</span>
Rect centerWindowRect = new Rect(Screen.width * 0.5f - windowWidth * 0.5f, Screen.height * 0.5f - windowHeight * 0.5f, windowWidth, windowHeight); <span class="comment">// create a cetered window rect</span>
GUILayout.Window(0, centerWindowRect, DrawDialogWindow, "Joystick Identification Required"); <span class="comment">// draw the window</span>
GUI.FocusWindow(0); <span class="comment">// focus the window</span>
<span class="comment">// Do not allow input during input delay to filter out holding a button down and assigning all joysticks to a single joystick id</span>
if(Time.time < nextInputAllowedTime) return;
<span class="comment">// Poll for a joystick button press to identify the joystick</span>
if(!ReInput.controllers.SetUnityJoystickIdFromAnyButtonPress(joysticksToIdentify.Peek().id)) {
return; <span class="comment">// no input detected</span>
}
<span class="comment">// Remove the joystick from the queue now that we've used it</span>
joysticksToIdentify.Dequeue();
<span class="comment">// Renew the input delay time after press</span>
SetInputDelay();
<span class="comment">// Finish up if the queue is empty</span>
if(joysticksToIdentify.Count == 0) {
Reset(); <span class="comment">// done</span>
}
}
private void DrawDialogWindow(int windowId) {
if(!identifyRequired) return; <span class="comment">// window displays 1 frame after it is closed, so this is required to prevent null references below</span>
<span class="comment">// Set up a temporary style with word wrap</span>
if(style == null) {
style = new GUIStyle(GUI.skin.label);
style.wordWrap = true;
}
<span class="comment">// Draw the window contents</span>
GUILayout.Space(15);
GUILayout.Label("A joystick has been attached or removed. You will need to identify each joystick by pressing a button on the controller listed below:", style);
Joystick joystick = joysticksToIdentify.Peek();
GUILayout.Label("Press any button on \"" + joystick.name + "\" now.", style);
GUILayout.FlexibleSpace();
if(GUILayout.Button("Skip")) {
joysticksToIdentify.Dequeue();
return;
}
}
private void Reset() {
joysticksToIdentify = null;
identifyRequired = false;
}
}
}</pre>
<hr />
<h3><a name="copying-input-config" id="copying-input-config"></a>Copying input configuration to another project</h3>
<p><a href="InputManager.html#how-data-is-stored">As explained in the Input Manager documentation</a>, Rewired's configuration settings are stored as serialized data inside the Rewired Input Manager Game Object. You can work with this Game Object like any other Game Object in Unity -- duplicate it, copy and paste it, create a prefab out of it, revert it to the prefab's default settings, etc. The settings contained in the GameObject will be carried over just like any other inspector settings when copied.</p>
<p><strong>Important:</strong> When copying assets in Unity to another project, you must also copy the asset's metadata or you will lose script references
and have other issues. There are several ways to properly copy a GameObject from one project to another:</p>
<ol>
<li>Export the object to a Unitypackage file and import it.</li>
<li>Create a prefab and copy the files in the OS file manager.</li>
<li>Copy the scene file in the OS file manager.</li>
</ol>
<p><strong>Export the object to a Unitypackage file and import it</strong></p>
<p> You can create a Unitypackage file from assets by selecting them in the Project window and going to the menu Assets -&gt; Export Package. This will create a Unitypackage from the selected Project assets which will include the necessary metadata. Be sure to uncheck &quot;include dependencies&quot; or it will export a bunch of files from the Rewired folder too.</p>
<p>Note that this does not work with a Game Object in the scene. In order to export a Unitypackage with the Rewired Input Manager in it, <a href="https://docs.unity3d.com/Manual/Prefabs.html" target="_blank">you must first create a prefab</a> out of the Rewired Input Manager, then export that prefab file.</p>
<p>In the new project, first, make sure Rewired is installed, then import the prefab by going to the menu Assets -&gt; Import Package -&gt; Custom Package and select the Unitypackage file you created.</p>
<p><strong>Create a prefab and copy the files in the OS file manager</strong></p>
<p>First, <a href="https://docs.unity3d.com/Manual/Prefabs.html" target="_blank">create a prefab</a> out of the Rewired Input Manager. Next, be sure that Visible Meta Files is enabled by going to the menu in the Unity Editor at Edit -&gt; Project Settings and selecting Visible Meta Files in the dropdown for Version Control. This will make Unity store its metadata in text files along with each asset instead of storing it in a location hidden away in the project. For each asset in your project, there will be an additional file with a .meta extension.</p>
<p>In the other project, make sure Rewired is installed. Then in the OS's file manager, select both the .prefab file you created and the .meta along side it in your first project and copy those to the Assets folder of your new project.</p>
<p><strong>Copy the scene file in the OS file manager</strong></p>
<p>If you don't want to create a prefab out of your Rewired Input Manager, you can instead copy the entire scene file to your new project in the OS file manager. Make sure Rewired is installed in your second project first, then copy the scene file. Open the scene file and the Rewired Input Manager will have all the same data as in your first project. Note that any other objects in your scene depending on assets or scripts that do not exist in this new project will be broken.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="hide-input-settings-launcher" id="hide-input-settings-launcher"></a>Hiding input settings on the Unity launcher</h3>
<p>Unity's launcher has a built-in input tab that allows players to customize input through the Unity input manager settings. With Rewired, this interface is not only irrelevant, it is problematic. Rewired sets up over 400 input manager entries to be able to get input from all controllers on Unity fallback platforms. The user should not be allowed to make changes to these default inputs. However Unity gives you no option to hide this input manager settings tab in the launcher. There are three options to deal with this:</p>
<ol>
<li>Disable the launcher. This has the disadvantage of preventing the user from changing the display resolution. To disable it, see Display Resolution Dialog setting in the <a href="https://docs.unity3d.com/Manual/class-PlayerSettingsStandalone.html" target="_blank">Unity Player settings</a>.</li>
<li>Hack the launcher to hide the input tab. There are no clear guidelines on how to do this, but <a href="https://forum.unity3d.com/threads/remove-input-section-from-launcher.141438/#post-991442" target="_blank">this forum post </a>shows how one user did it on Windows.</li>
<li>Disable the launcher completely and implement your own custom launcher. This allows you to give your user resolution display options as well. (The Unity player can be launched with command line options which set the resolution. <a href="https://docs.unity3d.com/Manual/CommandLineArguments.html">See the section Unity Standalone Comand Line Arguments for more information</a>.)</li>
</ol>
<p>&nbsp;</p>
<hr />
<h3><a name="optimization" id="optimization"></a>Optimizing performance</h3>
<p>For mobile platforms, squeezing out as much performance as possible is important. Here are some tips to help optimize Rewired's performance in your game:</p>
<ul>
<li>If you do not ever get input in FixedUpdate or OnGUI in your game, make sure these Update Loops are disabled in the <a href="RewiredEditor.html#Settings">Rewired Input Manager - Settings</a> page. Each additional update loop you have enabled increases CPU usage of Rewired.</li>
<li>The more <a href="Players.html">Players</a>, <a href="Actions.html">Actions</a>, enabled <a href="ControllerMaps.html">Controller Maps</a>, and ActionElementMap bindings you have, the more cpu time is required to evaluate input for each of these every update.</li>
<li><a href="#enabling-disabling-controller-maps">Disable all Controller Maps</a> that are not needed in the current game state. For example, if you have a <a href="MapCategories.html">Map Category</a> for UI controls, disable all UI <a href="ControllerMaps.html">Controller Maps</a> when the UI is not displayed.</li>
<li>Use integer contstants instead of string names for calling methods that take an Action, Map Category, or Layout. String comparison is slower than integer comparison. See <a href="#exporting-constants">Exporting constants for use in scripting</a> for information on how to get a list of constants.</li>
<li>If your game doesn't need keyboard or mouse input on certain platforms, disable one or both using the platform options in the <a href="RewiredEditor.html#Settings">Rewired Editor - Settings</a> page.</li>
</ul>
<p><strong>Input Events</strong><br />
If you are getting input by using input events, you are shifting the burden of polling for input events on Rewired instead of your scripts which increases its CPU usage. Not only that, but any code in your script that is run in the input event callback will be attributed by the profiler to InputManager_Base instead of your script.</p>
<p><strong>Unity Profiler, Debug Build, and Unity Editor Performance</strong><br />
Unity's profiler in Debug builds tends to report significantly inflated CPU usage for Rewired's InputManager_Base.Update. For example, testing shows that on the PlayStation Vita platform, the profiler will report CPU time up to 2x actual CPU time when timed manually in a Release build. <a href="Troubleshooting.html#xbox-one-profiler">XBox One can report CPU usage of 20x the CPU usage when using a Debug build vs a Development build.</a> In testing on Windows, release builds performed on average 2.5x faster in Unity 4.3 and 3.5x faster in Unity 5.4 than when timed inside the Unity editor. Rest assured, Rewired's core update loop has already been heavily optimized for performance.</p>
<p><strong>Deep Profile</strong><br />
If you enable Deep Profile in the Unity Profiler, InputManager_Base will show a drastically inflated CPU usage due to the fact that Deep Profile uses reflection to get method information. The depth of Rewired's call stack dramatically increases this performance penalty, making it look as if Rewired is taking a huge percentage of the processing time when in reality this is just profiler overhead.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="unity-ui" id="unity-ui"></a>Using Rewired to control Unity's new UI</h3>
<p><a href="RewiredStandaloneInputModule.html">See Rewired Standalone Input Module for information.</a></p>
<p>&nbsp;</p>
<hr />
<h3><a name="appletv-siri-remote" id="appletv-siri-remote"></a>Using Apple Siri Remote on Apple TV</h3>
<p>In general, the Siri Remote works like any other <a href="Controllers.html#joysticks">Joystick</a> in Rewired.</p>
<p>Special mappable elements on the Remote:</p>
<ul>
<li><strong>Touchpad X, Y</strong> - The X and Y values returned by the remote touchpad. This value is affected by the remote's current relative/absolute setting. This can be changed by setting <a href="https://docs.unity3d.com/Manual/tvOS.html" target="_blank">UnityEngine.Apple.TV.Remote.reportAbsoluteDpadValues</a>.</li>
<li><strong>Pitch</strong> - Returns a -1.0 to +1.0 value based on the current tilt of the remote. Returns 0 when the remote is held with the touchpad end of the remote facing directly up. Positive values correspond to a tilt of the remote toward the screen relative to the 0 position. Negative values correspond to a tilt of the remote away from the screen relative to the 0 position.</li>
<li><strong>Rotate</strong> - Returns a -1.0 to +1.0 value based on the current rotation of the remote. Returns 0 when the remote is held with the touchpad end of the remote facing directly up. Positive values correspond to a clockwise rotation of the remote from the 0 position. Negative values correspond to a counter-clockwise rotation of the remote from the 0 position.</li>
<li><strong>Acceleration X, Y, Z</strong> - Returns the acceleration X, Y, and Z vectors.</li>
<li><strong>Gravity X, Y, Z</strong> - Returns the Gravity X, Y, and Z vectors.</li>
</ul>
<p><strong>Joystick Assignment<br />
</strong>If using <a href="Controllers.html#joysticks">Joystick</a> auto-assignment (enabled by default), the Siri Remote is treated as any other <a href="Controllers.html#joysticks">Joystick</a> and will be assigned to the first <a href="Players.html">Player</a> found that needs a <a href="Controllers.html#joysticks">Joystick</a> assigned based on your current settings. If making a 1-player game, it is highly recommended that you raise the &quot;Max Joysticks Per Player&quot; setting to a large number such as 100 so that all attached <a href="Controllers.html#joysticks">Joysticks</a> will be assigned to the <a href="Players.html">Player</a>. This will allow the <a href="Players.html">Player</a> to use the Siri Remote or any gamepad attached without issue.</p>
<p>Please see the <a href="https://docs.unity3d.com/Manual/tvOS.html" target="_blank">Unity Documentation for Apple TV</a> for more information on special considerations for publishing on tvOS.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="using-arcadeguns-g500"></a>Using ArcadeGuns G-500 AimTrak Light Guns</h3>
<p>In order for the AimTrak G-500 to work with Rewired, the device must first be configured properly. See <a href="SupportedControllers.html#configuring-arcadeguns-g500">Supported Controllers - Configuring ArcadeGuns G-500 AimTrak Light Guns</a> for more information.</p>
<p>The data returned by the AimTrak light guns is not processed by Rewired into a screen-space or world-space coordinate system. The data is returned as it is received from the device. The data must be processed in your scripts in the appropriate manner for your intended use.</p>
<p>The easiest way to tell that the data is from the AimTrak would be to create 2 special <a href="Actions.html">Actions</a> specifically for this controller. Something like AimTrakX and AimTrackY. Then in your scripts you can simply check for these <a href="Actions.html">Actions</a> and process the values in to the appropriate coordinate system. Alternately, you could check an <a href="#get-contributing-input-sources">Action's contributing input sources</a> to determine if that <a href="Actions.html">Action</a> was contributed to by the AimTrak by checking the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/P_Rewired_Controller_hardwareTypeGuid.htm">joystick.hardwareTypeGuid</a> property. If the guid is 1708268b-3914-42c4-a339-7bf4fe83fde2, then it is from the AimTrak G-500. (This guid can be found in the HardwareJoystickMap controller definition.)</p>
<p>&nbsp;</p>
<hr />
<h3><a name="dualshock-4-special-features"></a>Using Sony DualShock 4 special features</h3>
<p>The Sony DualShock 4 supports vibration, gyro/accelerometer, touchpad, and changing the light color on Windows Standalone and OSX only at present (<a href="https://guavaman.com/projects/rewired/docs/RewiredEditor.html#Settings">Enhanced Device Support</a> option required.) If you're developing for the PlayStation 4, see the PS4 plugin documentation or <a href="#dualshock-4-special-features-common-interface">use the common interface to support both platforms simultaneously</a>.</p>
<p>The special features of this controller are accessible through the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ControllerExtensions_DualShock4Extension.htm">ControllerExtensions.DualShock4Extension</a> class.</p>
<p><a href="Examples.html#dualshock-4-special-features">Also see the Dual Shock 4 Special Features example.</a></p>
<p>An example on how to use this class is shown below:</p>
<pre class="code">
using Rewired;
using Rewired.ControllerExtensions;
class DS4Test {
<span class="comment">// Getting and setting various values on all DS4's assigned to this Player</span>
public void TestDS4(Player player) {
<span class="comment"> // Loop through all Joysticks assigned to this Player</span>
foreach(Joystick joystick in player.controllers.Joysticks) {
<span class="comment">// Get the Dual Shock 4 Controller Extension from the Joystick</span>
var ds4 = joystick.GetExtension&lt;DualShock4Extension&gt;();
if(ds4 == null) continue; <span class="comment">// this is not a DS4, skip it</span>
<span class="comment">// Get the accelerometer value</span>
Vector3 accelerometer = ds4.GetAccelerometerValue();
<span class="comment">// Get the gyroscope value</span>
Vector3 gyro = ds4.GetGyroscopeValue();
<span class="comment">// Get the controller orientation</span>
Quaternion orientation = ds4.GetOrientation();
<span class="comment">// Get the touch positions for both fingers</span>
bool touch1isTouching, touch2isTouching;
Vector2 touch1Pos, touch2Pos;
touch1isTouching = ds4.GetTouchPosition(0, out touch1Pos);
touch2isTouching = ds4.GetTouchPosition(1, out touch2Pos);
<span class="comment">// Get/Set vibration
// Note: Vibration can also be set in a generic way through Joystick.SetVibration</span>
float vibration = ds4.GetVibration(DualShock4MotorType.WeakMotor);
ds4.SetVibration(DualShock4MotorType.StrongMotor, 1.0f); <span class="comment">// set vibration on a single motor by type</span>
ds4.SetVibration(1.0f, 1.0f); <span class="comment">// set vibration on both motors simultaneously</span>
ds4.StopVibration(); <span class="comment">// stop all vibration</span>
<span class="comment">// Get the light color</span>
Color lightColor = ds4.GetLightColor();
<span class="comment">// Set the light color</span>
ds4.SetLightColor(new Color(1.0f, 1.0f, 0.0f, 0.5f)); <span class="comment">// alpha is multiplied by rgb to get final value</span>
<span class="comment">// Set the light flash</span>
ds4.SetLightFlash(1.0f); // flash light every 1 second
ds4.StopLightFlast(); // stop light flashing
<span class="comment">// Get the battery level</span>
float battery = ds4.batteryLevel;
}
}
}</pre>
<p><strong>Common Interface<br />
</strong><a name="dualshock-4-special-features-common-interface" id="dualshock-4-special-features-common-interface"></a>You can use the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ControllerExtensions_IDualShock4Extension.htm">ControllerExtensions.IDualShock4Extension</a> interface instead if you want to run the same code on the PS4 platform and a desktop platform. (This interface also works with the Sony DualSense controller.) The controller does not support all the same features on both the desktop and PS4 platforms, but the common features between the two platforms are supported through the interface. Cast to the concrete extension class if you need access to features that are only supported on that version.</p>
<pre class="code">
<span class="comment">// Get the Dual Shock 4 Extension interface from the Joystick</span>
var ds4 = joystick.GetExtension&lt;IDualShock4Extension&gt;();
if(ds4 == null) return;
<span class="comment">// Features that are available on all platforms are accessible through the interface</span>
Quaternion orientation = ds4.GetOrientation();
Vector3 accelerometer = ds4.GetAccelerometerValue();
ds4.SetLightColor(Color.red);
<span class="comment">// Cast to the concrete type to get access to the feature not available on the interface</span>
if(ds4 is DualShock4Extension) { <span class="comment">// desktop version</span>
<span class="comment">// Desktop-only code</span>
DualShock4Extension desktopDs4 = (DualShock4Extension)ds4;
float batteryLevel = desktopDs4.batteryLevel;<span class="comment"></span>
} else if(ds4 is Rewired.Platforms.PS4.PS4GamepadExtension) { <span class="comment">// PS4 version</span>
<span class="comment">// PS4-only code</span>
Rewired.Platforms.PS4.PS4GamepadExtension ps4ds4 = (Rewired.Platforms.PS4.PS4GamepadExtension)ds4;
<span class="comment">// PS4 platform code goes here...</span>
}<br /></pre>
<p>&nbsp;</p>
<hr />
<h3><a name="dualsense-special-features" id="dualsense-special-features"></a>Using Sony DualSense special features</h3>
<p>The Sony DualSense supports vibration, trigger effects, gyro/accelerometer, touchpad, and changing the light color on Windows Standalone and OSX only at present (<a href="https://guavaman.com/projects/rewired/docs/RewiredEditor.html#Settings">Enhanced Device Support</a> option required.) If you're developing for the PlayStation 5, see the PS5 plugin documentation or <a href="#dualsense-special-features-common-interface">use the common interface to support both platforms simultaneously</a>.</p>
<p>The special features of this controller are accessible through the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ControllerExtensions_DualSenseExtension.htm">ControllerExtensions.DualSenseExtension</a> class.</p>
<p>You can <a href="#dualshock-4-special-features-common-interface">use the common DS4 interface to support the DualShock 4 and DualSense simultaneously</a>.</p>
<p><a href="Examples.html#dualshock-4-special-features">Also see the Dual Shock 4 Special Features example.</a></p>
<p>See the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/N_Rewired_ControllerExtensions.htm">ControllerExtensions</a> namespace for different DualSense trigger effect structs.</p>
<p>An example on how to use this class is shown below:</p>
<pre class="code">
using Rewired;
using Rewired.ControllerExtensions;
class DualSenseTest {
<span class="comment">// Getting and setting various values on all DualSense's assigned to this Player</span>
public void TestDualSense(Player player) {
<span class="comment"> // Loop through all Joysticks assigned to this Player</span>
foreach(Joystick joystick in player.controllers.Joysticks) {
<span class="comment">// Get the DualSense Controller Extension from the Joystick</span>
var ds = joystick.GetExtension&lt;DualSenseExtension&gt;();
if(ds == null) continue; <span class="comment">// this is not a DualSense, skip it</span>
<span class="comment">// Get the accelerometer value</span>
Vector3 accelerometer = ds.GetAccelerometerValue();
<span class="comment">// Get the gyroscope value</span>
Vector3 gyro = ds.GetGyroscopeValue();
<span class="comment">// Get the controller orientation</span>
Quaternion orientation = ds.GetOrientation();
<span class="comment">// Get the touch positions for both fingers</span>
bool touch1isTouching, touch2isTouching;
Vector2 touch1Pos, touch2Pos;
touch1isTouching = ds4.GetTouchPosition(0, out touch1Pos);
touch2isTouching = ds4.GetTouchPosition(1, out touch2Pos);
<span class="comment">// Get/Set vibration
// Note: Vibration can also be set in a generic way through Joystick.SetVibration</span>
float vibration = ds.GetVibration(DualShock4MotorType.WeakMotor);
ds.SetVibration(DualShock4MotorType.StrongMotor, 1.0f); <span class="comment">// set vibration on a single motor by type</span>
ds.SetVibration(1.0f, 1.0f); <span class="comment">// set vibration on both motors simultaneously</span>
ds.StopVibration(); <span class="comment">// stop all vibration</span>
<span class="comment">// Trigger Effects</span>
<span class="comment">// Set a feedback trigger effect in the right trigger</span>
ds.SetTriggerEffect(DualSenseTriggerType.Right, new DualSenseTriggerEffectFeedback() {
position = 3,
strength = 8
});<span class="comment"></span>
<span class="comment">// Set a multi-position feedback trigger effect in the left trigger</span>
<span class="comment">// Strength changes throughout trigger press</span>
var strength = new DualSenseTriggerEffectPositionValueSet();
strength[0] = 5;
strength[1] = 6;
strength[2] = 7;
strength[3] = 8;
strength[4] = 0;
strength[5] = 0;
strength[6] = 0;
strength[7] = 8;
strength[8] = 8;
strength[9] = 0;
ds.SetTriggerEffect(
DualSenseTriggerType.Left,
new DualSenseTriggerEffectMultiplePositionFeedback() {
strength = strength
}
);
<span class="comment">// Get the light color</span>
Color lightColor = ds.GetLightColor();
<span class="comment">// Set the light color</span>
ds.SetLightColor(new Color(1.0f, 1.0f, 0.0f, 0.5f)); <span class="comment">// alpha is multiplied by rgb to get final value</span>
<span class="comment">// Set the player lights</span>
ds.playerLights = DualSensePlayerLightFlags.Two | DualSensePlayerLightFlags.Four; <span class="comment">// enable lights 2 and 4 to signify Player 2</span>
<span class="comment">// Enable the microphone button light</span>
ds.microphoneLightMode = DualSenseMicrophoneLightMode.On;
<span class="comment">// Set the player lights and microphone light brigtness</span>
ds.otherLightBrightness = DualSenseOtherLightBrightness.Low;
<span class="comment">// Get battery information</span>
float battery = ds.batteryLevel;
bool batteryCharging = ds.batteryCharging;
}
}
}</pre>
<p><strong>Common Interface<br />
</strong><a name="dualsense-special-features-common-interface" id="dualsense-special-features-common-interface"></a>You can use the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ControllerExtensions_IDualSenseExtension.htm">ControllerExtensions.IDualSenseExtension</a> interface instead if you want to run the same code on the PS5 platform and a desktop platforms (requires Rewired PS5 Plugin v4+). The controller does not support all the same features on both the desktop and PS5 platforms, but the common features between the two platforms are supported through the interface. Cast to the concrete extension class if you need access to features that are only supported on that version.</p>
<pre class="code">
<span class="comment">// Get the Dual Sense Extension interface from the Joystick</span>
var ds = joystick.GetExtension&lt;IDualSenseExtension&gt;();
if(ds == null) return;
<span class="comment">// Features that are available on all platforms are accessible through the interface</span>
Quaternion orientation = ds.GetOrientation();
Vector3 accelerometer = ds.GetAccelerometerValue();
ds.SetLightColor(Color.red);
<span class="comment">// Cast to the concrete type to get access to the feature not available on the interface</span>
if(ds is DualSenseExtension) { <span class="comment">// desktop version</span>
<span class="comment">// Desktop-only code</span>
DualSenseExtension desktopDs = (DualSenseExtension)ds;
float batteryLevel = desktopDs.batteryLevel;<span class="comment"></span>
} else if(ds is Rewired.Platforms.PS5.PS5GamepadExtension) { <span class="comment">// PS5 version</span>
<span class="comment">// PS5-only code</span>
Rewired.Platforms.PS5.PS5GamepadExtension ps5ds = (Rewired.Platforms.PS5.PS5GamepadExtension)ds;
<span class="comment">// PS5 platform code goes here...</span>
}</pre>
<p>&nbsp;</p>
<hr />
<h3><a name="nintendo-switch-controller-special-features" id="nintendo-switch-controller-special-features"></a>Using Nintendo Switch controller special features</h3>
<p>Nintendo Switch controllers support vibration on Windows Standalone and OSX only at present (<a href="https://guavaman.com/projects/rewired/docs/RewiredEditor.html#Settings">Enhanced Device Support</a> option required.) If you're developing for the Nintendo Switch platform, see the Rewired Nintendo Switch plugin documentation.</p>
<p>The special features of this controller are accessible through the following Controller Extension classes:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ControllerExtensions_NintendoSwitchGamepadExtension.htm">ControllerExtensions.NintendoSwitchGamepadExtension</a> class - Base class for all Nintendo Switch gamepad Controller Extensions.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ControllerExtensions_NintendoSwitchProControllerExtension.htm">ControllerExtensions.NintendoSwitchProControllerExtension</a> class.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ControllerExtensions_NintendoSwitchJoyConExtension.htm">ControllerExtensions.NintendoSwitchJoyConExtension</a> class.</li>
</ul>
<p>An example on how to use this class is shown below:</p>
<pre class="code">
using Rewired;
using Rewired.ControllerExtensions;
class NintendoSwitchControllerTest {
<span class="comment">// Getting and setting various values on all Nintendo Switch controllers assigned to this Player</span>
public void Test(Player player) {
<span class="comment"> // Loop through all Joysticks assigned to this Player</span>
foreach(Joystick joystick in player.controllers.Joysticks) {
<span class="comment">// Get the Controller Extension from the Joystick</span>
var ext = joystick.GetExtension&lt;NintendoSwitchGamepadExtension&gt;();
if(ext == null) continue; <span class="comment">// this is not a Nintendo Switch controller, skip it</span>
<span class="comment">// Get/Set vibration
// Note: Vibration can also be set in a generic way through Joystick.SetVibration</span>
NintendoSwitchGamepadVibration vibration = NintendoSwitchGamepadVibration.Create(
1.0f, <span class="comment">// low amplitude</span>
120, <span class="comment">// low frequency (Hz)</span>
1.0f, <span class="comment">// high amplitude</span>
320 <span class="comment">// high frequency (Hz)</span>
);
ext.SetVibration(0, vibration); <span class="comment">// set vibration</span>
if(ext.vibrationMotorCount &gt; 1) ext.SetVibration(1, vibration);
<span class="comment">// Use Joy-Con special features</span>
var joyConExt = joystick.GetExtension&lt;NintendoSwitchJoyConExtension&gt;();
if(joyConExt == null) continue; <span class="comment">// this is not a Joy-Con</span>
<span class="comment">// Set Joy-Con grip style to vertical</span>
<span class="comment"> // This will change the stick axis directions, and directional buttons
// will be swapped on the left Joy-Con.</span>
joyConExt.joyConGripStyle = NintendoSwitchJoyConGripStyle.Vertical;
<span class="comment">// Determine if this is the left or right Joy-Con</span>
if(joyConExt.joyConType == NintendoSwitchJoyConType.Left) {
<span class="comment">// This is the left Joy-Con</span>
}
}
}
}</pre>
<p>&nbsp;</p>
<hr />
<h3><a name="raildriver-special-features" id="raildriver-special-features"></a>Using P.I. Engineering Rail Driver special features</h3>
<p>The P.I. Engineering RailDriver supports all features of the device (<a href="https://guavaman.com/projects/rewired/docs/RewiredEditor.html#Settings">Enhanced Device Support</a> option required.)</p>
<p>The special features of this controller are accessible through the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_ControllerExtensions_RailDriverExtension.htm">Rewired.ControllerExtensions.RailDriverExtension</a> class.</p>
<p>An example on how to use this class is shown below:</p>
<pre class="code">
using Rewired;
using Rewired.ControllerExtensions;
class RailDriverTest {
<span class="comment">// Getting and setting various values on all RailDrivers assigned to this Player</span>
public void TestRailDriver(Player player) {
<span class="comment"> // Loop through all Joysticks assigned to this Player</span>
foreach(Joystick joystick in player.controllers.Joysticks) {
<span class="comment">// Get the RailDriver Controller Extension from the Joystick</span>
var rd = joystick.GetExtension&lt;Rewired.ControllerExtensions.RailDriverExtension&gt;();
if(rd == null) continue; <span class="comment">// this is not a RailDriver, skip it</span>
<span class="comment">// Enable/disable speaker</span>
rd.speakerEnabled = true;
<span class="comment">// Set LED display</span>
int ledIndex = 0;
byte ledDigitByte = 1; <span class="comment">// see RailDriver documentation for information on the digit byte</span>
rd.SetLEDDisplay(0, ledDigitByte);
}
}
}</pre>
<p>&nbsp;</p>
<hr />
<h3><a name="xbox-one-controller-special-features" id="raildriver-special-features2"></a>Using XBox One controller special features on XBox One platform</h3>
<p>Special controller features of the XBox One gamepad such as vibration can be accessed via the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Platforms_XboxOne_XboxOneGamepadExtension.htm">XboxOneGamepadExtension</a> class available in the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Joystick.htm">Joystick</a> class as seen in the example below. Note that the platform input source must be set to Native and Disable Native Input must be set to false or no special features will be available.
<pre class="code">
using Rewired;
using Rewired.Platforms.XboxOne;
class XBoxOneTest {
void MyMethod() {
<span class="comment">// Set vibration in all controllers in player</span>
foreach(Joystick joystick in player.controllers.Joysticks) {
<span class="comment">// Get the ControllerExtension for Xbox One and set left gamepad motor to full value</span>
var extension = joystick.GetExtension&lt;XboxOneGamepadExtension&gt;();
if(extension != null) { <span class="comment">// this is an Xbox One gamepad on the Xbox One platform</span>
<span class="comment">// Set vibration using the XboxOneGamepadMotorType enum</span>
extension.SetVibration(XboxOneGamepadMotorType.LeftMotor, 1.0f);
} else { <span class="comment">// any other controller</span>
<span class="comment"> // Vibration can also be set in a more generic way through
// Joystick.SetVibration by using the motor index</span>
<span class="comment">// This method can also be used to set vibration on the Xbox One Platform</span>
<span class="comment">// Alternately, you can set vibration on all Joysticks at once through the Player class.</span>
joystick.SetVibration(0, 1.0f); <span class="comment">// set first motor to full value</span>
}<br /> }
}
}</pre>
<p>&nbsp;</p>
<hr />
<h4><a name="apple-game-controller-framework" id="apple-game-controller-framework"></a>Apple&nbsp;Game Controller Framework special features</h4>
<p>If the Apple Game Controller Framework input source is being used on the platform, certain features are exposed through the API.</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/T_Rewired_Platforms_Apple_GameController_GCControllerInput.htm">GCControllerInput</a> - Provides access to input-related methods and settings at runtime.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Apple_GameController_GCControllerInput_ControllerAssignment.htm">GCControllerInput.ControllerAssignment</a> - Provides access to controller assignment-related settings at runtime.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Apple_GameController_GCControllerExtension.htm">GCControllerExtension</a> - Allows access to controller-specific functions.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Apple_GameController_GCControllerDualShock4Extension.htm">GCControllerDualShock4Extension</a> - Allows access to controller-specific functions for the Sony Dual Shock 4 controller.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Apple_GameController_GCControllerDualSenseExtension.htm">GCControllerDualSenseExtension</a> - Allows access to controller-specific functions for the Sony Dual Sense controller.</li>
</ul>
<p><strong>General Usage</strong></p>
<p>Code that makes use of the Game Controller Framework should be enclosed in an #if directive for the specific build targets because these functions are not included on build targets that do not support the Game Controller Framework:</p>
<pre class="code">#if (UNITY_OSX &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_OSX
<span class="comment">// Some GCController specific code</span>
GCControllerExtension gcControllerExtension = controller.GetExtension&lt;GCControllerExtension&gt;();
#endif</pre>
<p>All functions are in the namespace Rewired.Platforms.Apple.GameController. Add this in a using statement which is enclosed in an #if directive for the specific build targets.</p>
<pre class="code">#if (UNITY_OSX &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_OSX
using Rewired.Platforms.Apple.GameController;
#endif</pre>
<p><strong>Controller Extension</strong></p>
<p>The <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Apple_GameController_GCControllerExtension.htm">GCControllerExtension</a> exposes information specific to the Game Controller Framework. Some examples include:</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Platforms_Apple_GameController_GCControllerExtension_GetElementUnmappedLocalizedName.htm">nativePlayerIndex</a> - Gets the native player index. This corresponds to playerIndex in the Game Controller framework. This is only useful for direct interaction with the Game Controller framework.</li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Platforms_Apple_GameController_GCControllerExtension_GetElementUnmappedLocalizedName.htm">nativeDevicePointer</a> - Gets the native pointer to the GCController object. This is only useful for direct interaction with the Game Controller framework. If the pointer is unavailable or invalid, returns IntPtr.Zero.</li>
</ul>
<p><strong>Game Controller Framework Labels and Symbols</strong></p>
<p>The GCControllerExtension exposes functions to look up Game Controller Framework labels and symbols for controller elements. This matters because the Game Controller Framework has the ability to remap elements on the controller at the system level. Rewired was never designed to work with a system where controller elements can change in identity -- for example, the B button on the controller becomes the Y button because the user remapped it in the OS. This goes against the basic design of Rewired's controller recognition system which must be able to identify controller elements based on a pre-defined manually-created controller definition. To address this discrepancy, functions are exposed to get the Game Controller Framework element identifying information that corresponds to a Rewired Controller Element Identifier. The Game Controller Framework provides unmapped and remapped element label strings and unmapped and remapped element symbol strings. This is useful if you need to display the system-remapped glyph for a controller element to the user for example. The string values come from the Game Controller Framework, so refer to Apple's documentation for information about these strings and how to use them.</p>
<ul>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Platforms_Apple_GameController_GCControllerExtension_GetElementSfSymbolsName.htm">GetElementSfSymbolsName</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Platforms_Apple_GameController_GCControllerExtension_GetElementUnmappedLocalizedName.htm">GetElementUnmappedSfSymbolsName</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Platforms_Apple_GameController_GCControllerExtension_GetElementLocalizedName.htm">GetElementLocalizedName</a></li>
<li><a href="https://guavaman.com/projects/rewired/docs/api-reference/html/M_Rewired_Platforms_Apple_GameController_GCControllerExtension_GetElementUnmappedLocalizedName.htm">GetElementUnmappedLocalizedName</a></li>
</ul>
<p><strong>Game Controller Framework Player</strong></p>
<p>The Apple Game Controller Framework has its own concept of a player. Each player has an index. This is optional. If you want to use Apple's player system and you want Rewired's Players to be associated to specific Game Controller Framework player indices, you can create Rewired to GCController player association mappings using <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Apple_GameController_GCControllerInput_ControllerAssignment.htm">GCControllerInput.ControllerAssignment</a>.</p>
<p>By default, if Joystick Auto-Assignment is enabled and Settings -&gt; OSX -&gt; Assign Joysticks by System Player Id is enabled, Rewired will create a 1:1 Rewired Player to GCController player association by index automatically. This can be modified through <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Apple_GameController_GCControllerInput_ControllerAssignment.htm">GCControllerInput.ControllerAssignment</a>.</p>
<p>NOTE: This feature only applies to devices handled by the Apple Game Controller Framework. It does not apply to HID devices handled by IO Kit or any other input source. On OSX, this feature works best when the Primary Input Source is set to Game Controller and not Native + Use Game Controller Framework. This is because the Native input source uses I/O Kit and will include HID devices not supported by Game Controller Framework, and these devices do not have a GCController player index associated with them.</p>
<p><strong>Known Issues</strong></p>
<p>Apple's Game Controller Framework has a number of serious issues. See <a href="KnownIssues.html#osx-gccontroller-vibration-connection-bug">Known Issues</a> for more information.</p>
<p>&nbsp;</p>
<hr />
<h3><a name="raw-input-controller-extension" id="raw-input-controller-extension"></a>Additional Windows Raw Input controller information</h3>
<p>Additional information about controllers on Windows Standalone when using Raw Input as the primary input source can be obtained through the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Windows_RawInput_RawInputControllerExtension.htm">RawInputControllerExtension</a>. This is only useful if you need to get some kind of low-level information about the controller for special purposes such as trying to support some special features (such as force feedback) of a controller through an SDK independently of Rewired while still using Rewired for input.</p>
<p>If Use XInput is enabled, compatible controllers will implement XInputControllerExtension instead. <a href="#xinput-controller-extension">See this for more information</a>.</p>
<p>If Use Windows Gaming Input is enabled, compatible controllers will implement WindowsGamingInputControllerExtension instead. <a href="#wgi-controller-extension">See this for more information</a>.</p>
<p>Note that if Enhanced Device Support is enabled and the device is supported by Enhanced Device Support, it will have its own Controller Extension and will not implement RawInputControllerExtension.</p>
<p>All classes are in the namespace Rewired.Platforms.Windows.RawInput.</p>
<pre class="code">#if (UNITY_STANDALONE_WIN &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_WIN
using Rewired.Platforms.Windows.RawInput;
#endif</pre>
<p>The RawInputControllerExtension is only available on the Windows Standalone platform and therefore any reference to the class must be enclosed in an #if directive that includes the code only on the Windows Standalone platform.</p>
<p>To access information, get the Controller Extension from the Joystick:</p>
<pre class="code">
<span class="comment"></span>foreach(Joystick joystick in player.controllers.Joysticks) {
#if (UNITY_STANDALONE_WIN &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_WIN
<span class="comment">// Get the ControllerExtension for Raw Input</span>
var extension = joystick.GetExtension&lt;RawInputControllerExtension&gt;();
if(extension != null) {
<span class="comment">// Log the device path</span>
Debug.Log(extension.devicePath);
}
#endif<br />}
</pre>
<p>&nbsp;</p>
<hr />
<h3><a name="direct-input-controller-extension" id="direct-input-controller-extension"></a>Additional Windows Direct Input controller information</h3>
<p>Additional information about controllers on Windows Standalone when using Direct Input as the primary input source can be obtained through the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Windows_DirectInput_DirectInputControllerExtension.htm">DirectInputControllerExtension</a>. This is only useful if you need to get some kind of low-level information about the controller for special purposes such as trying to support some special features (such as force feedback) of a controller through an SDK independently of Rewired while still using Rewired for input.</p>
<p>If Use XInput is enabled, compatible controllers will implement XInputControllerExtension instead. <a href="#xinput-controller-extension">See this for more information</a>.</p>
<p>If Use Windows Gaming Input is enabled, compatible controllers will implement WindowsGamingInputControllerExtension instead. <a href="#wgi-controller-extension">See this for more information</a>.</p>
<p>All classes are in the namespace Rewired.Platforms.Windows.DirectInput.</p>
<pre class="code">#if (UNITY_STANDALONE_WIN &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_WIN
using Rewired.Platforms.Windows.DirectInput;
#endif</pre>
<p>The DirectInputControllerExtension is only available on the Windows Standalone platform and therefore any reference to the class must be enclosed in an #if directive that includes the code only on the Windows Standalone platform.</p>
<p>To access information, get the Controller Extension from the Joystick:</p>
<pre class="code">
<span class="comment"></span>foreach(Joystick joystick in player.controllers.Joysticks) {
#if (UNITY_STANDALONE_WIN &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_WIN
<span class="comment">// Get the ControllerExtension for Direct Input</span>
var extension = joystick.GetExtension&lt;DirectInputControllerExtension&gt;();
if(extension != null) {
<span class="comment">// Log the interface path</span>
Debug.Log(extension.interfacePath);
}
#endif
}<br /></pre>
<p>&nbsp;</p>
<hr />
<h3><a name="xinput-controller-extension" id="xinput-controller-extension"></a>Additional Windows XInput controller information</h3>
<p>Additional information about controllers on Windows Standalone when using XInput as the primary input source and when Use XInput is enabled when using Raw Input or Direct Input as the primary input source can be obtained through the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Windows_XInput_XInputControllerExtension.htm">XInputControllerExtension</a>. This is only useful if you need to get some kind of low-level information about the controller for special purposes.</p>
<p>All classes are in the namespace Rewired.Platforms.Windows.XInput.</p>
<pre class="code">#if (UNITY_STANDALONE_WIN &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_WIN
using Rewired.Platforms.Windows.XInput;
#endif</pre>
<p>The XInputControllerExtension is only available on the Windows Standalone platform and therefore any reference to the class must be enclosed in an #if directive that includes the code only on the Windows Standalone platform.</p>
<p>To access information, get the Controller Extension from the Joystick:</p>
<pre class="code">
<span class="comment"></span>foreach(Joystick joystick in player.controllers.Joysticks) {
#if (UNITY_STANDALONE_WIN &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_WIN
<span class="comment">// Get the ControllerExtension for XInput</span>
var extension = joystick.GetExtension&lt;XInputControllerExtension&gt;();
if(extension != null) {
<span class="comment">// Log the user index</span>
Debug.Log(extension.userIndex);
}
#endif
}<br />
</pre>
<p></p>
<p>&nbsp;</p>
<hr />
<h3><a name="wgi-controller-extension" id="wgi-controller-extension"></a>Additional Windows Windows Gaming Input controller information</h3>
<p>Additional information about controllers on Windows Standalone (when using Windows Gaming Input as the primary input source and when Use Windows Gaming Input is enabled when using Raw Input or Direct Input as the primary input source) and on Windows UWP (when Use Gamepad API is enabled) can be obtained through the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Microsoft_WindowsGamingInput_WindowsGamingInputControllerExtension.htm">WindowsGamingInputControllerExtension</a>. This is only useful if you need to get some kind of low-level information about the controller for special purposes.</p>
<p>All classes are in the namespace Rewired.Platforms.Microsoft.WindowsGamingInput.</p>
<pre class="code">#if (UNITY_STANDALONE_WIN &amp;&amp; !UNITY_EDITOR) || (UNITY_WSA &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_WIN
using Rewired.Platforms.Microsoft.WindowsGamingInput;
#endif</pre>
<p>The WindowsGamingInputControllerExtension is available on the Windows Standalone and Windows UWP platforms, and therefore any reference to the class must be enclosed in an #if directive that includes the code only on those platforms.</p>
<p>To access information, get the Controller Extension from the Joystick:</p>
<pre class="code">
<span class="comment"></span>foreach(Joystick joystick in player.controllers.Joysticks) {
#if (UNITY_STANDALONE_WIN &amp;&amp; !UNITY_EDITOR) || (UNITY_WSA &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_WIN
<span class="comment">// Get the ControllerExtension for WindowsGamingInput</span>
var extension = joystick.GetExtension&lt;WindowsGamingInputControllerExtension&gt;();
if(extension != null) {
<span class="comment">// Log the WindowsGamingInput device type</span>
Debug.Log(extension.deviceType);
}
#endif
}<br /></pre>
<p></p>
<p></p>
<hr />
<h3><a name="uwp-controller-extension" id="uwp-controller-extension"></a>Additional Universal Windows Platform (UWP) controller information</h3>
<p>Additional information about controllers on Universal Windows Platform when using Native as the primary input source can be obtained through the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_UWP_HID_HIDControllerExtension.htm">HIDControllerExtension</a> (if Use HID API is enabled) and <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Microsoft_WindowsGamingInput_WindowsGamingInputControllerExtension.htm">WindowsGamingInputControllerExtension</a> (if Use Gamepad API is enabled). This is only useful if you need to get some kind of low-level information about the controller for special purposes.</p>
<p><a href="#wgi-controller-extension">See this for more information about using the WindowsGamingInputControllerExtension.</a></p>
<p>To use the HIDControllerExtension, all classes are in the namespace Rewired.Platforms.UWP.HID.</p>
<pre class="code">#if (UNITY_WSA &amp;&amp; !UNITY_EDITOR)
using Rewired.Platforms.UWP.HID;
#endif</pre>
<p>The IOKitControllerExtension is only available on the MacOS Standalone platform and therefore any reference to the class must be enclosed in an #if directive that includes the code only on the MacOS Standalone platform.</p>
<p>To access information, get the Controller Extension from the Joystick:</p>
<pre class="code">
<span class="comment"></span>foreach(Joystick joystick in player.controllers.Joysticks) {
#if (UNITY_WSA &amp;&amp; !UNITY_EDITOR)
<span class="comment">// Get the ControllerExtension for UWP HID</span>
var extension = joystick.GetExtension&lt;HIDControllerExtension&gt;();
if(extension != null) {
<span class="comment">// Log the product id</span>
Debug.Log(extension.productId);
}
#endif
}<br /></pre>
<p></p>
<p></p>
<hr />
<h3><a name="macos-controller-extension" id="macos-controller-extension"></a>Additional MacOS controller information</h3>
<p>Additional information about controllers on MacOS Standalone when using Native as the primary input source can be obtained through the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_MacOS_IOKit_IOKitControllerExtension.htm">IOKitControllerExtension</a> and <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Apple_GameController_GCControllerExtension.htm">GCControllerExtension</a> (if Use Game Controller Framework is enabled.) This is only useful if you need to get some kind of low-level information about the controller for special purposes such as trying to support some special features (such as force feedback) of a controller through an SDK independently of Rewired while still using Rewired for input.</p>
<p>If Use Game Controller Framework is enabled or the primary input is set to Game Controller Framework, compatible controllers will implement GCControllerExtension instead. <a href="#apple-game-controller-framework">See this for more information</a>.</p>
<p>Note that if Enhanced Device Support is enabled and the device is supported by Enhanced Device Support, it will have its own Controller Extension and will not implement IOKitControllerExtension.</p>
<p>All classes are in the namespace Rewired.Platforms.MacOS.IOKit.</p>
<pre class="code">#if (UNITY_STANDALONE_OSX &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_OSX
using Rewired.Platforms.MacOS.IOKit;
#endif</pre>
<p>The IOKitControllerExtension is only available on the MacOS Standalone platform and therefore any reference to the class must be enclosed in an #if directive that includes the code only on the MacOS Standalone platform.</p>
<p>To access information, get the Controller Extension from the Joystick:</p>
<pre class="code">
<span class="comment"></span>foreach(Joystick joystick in player.controllers.Joysticks) {
#if (UNITY_STANDALONE_OSX &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_OSX
<span class="comment">// Get the ControllerExtension for IO Kit</span>
var extension = joystick.GetExtension&lt;IOKitControllerExtension&gt;();
if(extension != null) {
<span class="comment">// Log the device service</span>
Debug.Log(extension.deviceService);
}
#endif
}<br /></pre>
<p></p>
<p></p>
<hr />
<h3><a name="linux-controller-extension" id="linux-controller-extension"></a>Additional Linux controller information</h3>
<p>Additional information about controllers on Linux Standalone when using Native as the primary input source can be obtained through the <a href="https://guavaman.com/projects/rewired/docs/api-reference/html/Properties_T_Rewired_Platforms_Linux_Udev_UdevControllerExtension.htm">UdevControllerExtension</a>. This is only useful if you need to get some kind of low-level information about the controller for special purposes such as trying to support some special features (such as force feedback) of a controller through an SDK independently of Rewired while still using Rewired for input.</p>
<p>All classes are in the namespace Rewired.Platforms.Linux.Udev.</p>
<pre class="code">#if (UNITY_STANDALONE_LINUX &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_LINUX
using Rewired.Platforms.Linux.Udev;
#endif</pre>
<p>The UdevControllerExtension is only available on the Linux Standalone platform and therefore any reference to the class must be enclosed in an #if directive that includes the code only on the Linux Standalone platform.</p>
<p>To access information, get the Controller Extension from the Joystick:</p>
<pre class="code">
<span class="comment"></span>foreach(Joystick joystick in player.controllers.Joysticks) {
#if (UNITY_STANDALONE_LINUX &amp;&amp; !UNITY_EDITOR) || UNITY_EDITOR_LINUX
<span class="comment">// Get the ControllerExtension for Udev</span>
var extension = joystick.GetExtension&lt;UdevControllerExtension&gt;();
if(extension != null) {
<span class="comment">// Log the system path</span>
Debug.Log(extension.systemPath);
}
#endif
}<br /></pre>
<p></p>
<p></p>
<hr />
<h3><a name="enhanced-device-support-linux" id="enhanced-device-support-linux"></a>Enhanced Device Support permissions on Linux</h3>
<p>In order for Enhanced Device Support to work on Linux, the end-user must set up UDEV rules to allow applications to access the raw HID device. Create a file named 99-rewired-permissions.rules in /etc/udev/rules.d/ with the following contents and reboot:</p>
<pre class="code"># Sony DualShock 4
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, ATTRS{idVendor}==&quot;054c&quot;, ATTRS{idProduct}==&quot;05c4&quot;, MODE=&quot;0666&quot;
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, KERNELS==&quot;*054C:05C4*&quot;, MODE=&quot;0666&quot;
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, ATTRS{idVendor}==&quot;054c&quot;, ATTRS{idProduct}==&quot;09cc&quot;, MODE=&quot;0666&quot;
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, KERNELS==&quot;*054C:09CC*&quot;, MODE=&quot;0666&quot;
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, ATTRS{idVendor}==&quot;054c&quot;, ATTRS{idProduct}==&quot;0ba0&quot;, MODE=&quot;0666&quot;
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, KERNELS==&quot;*054C:0BA0*&quot;, MODE=&quot;0666&quot;
# Sony DualSense
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, ATTRS{idVendor}==&quot;054c&quot;, ATTRS{idProduct}==&quot;0ce6&quot;, MODE=&quot;0666&quot;
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, KERNELS==&quot;*054C:0CE6*&quot;, MODE=&quot;0666&quot;
# Sony DualSense Edge
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, ATTRS{idVendor}==&quot;054c&quot;, ATTRS{idProduct}==&quot;0df2&quot;, MODE=&quot;0666&quot;
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, KERNELS==&quot;*054C:0DF2*&quot;, MODE=&quot;0666&quot;
# Nintendo Pro Controller
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, ATTRS{idVendor}==&quot;057e&quot;, ATTRS{idProduct}==&quot;2009&quot;, MODE=&quot;0666&quot;
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, KERNELS==&quot;*057E:2009*&quot;, MODE=&quot;0666&quot;
# Nintendo Joy-Con (L)
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, ATTRS{idVendor}==&quot;057e&quot;, ATTRS{idProduct}==&quot;2006&quot;, MODE=&quot;0666&quot;
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, KERNELS==&quot;*057E:2006*&quot;, MODE=&quot;0666&quot;
# Nintendo Joy-Con (R)
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, ATTRS{idVendor}==&quot;057e&quot;, ATTRS{idProduct}==&quot;2007&quot;, MODE=&quot;0666&quot;
KERNEL==&quot;hidraw*&quot;, SUBSYSTEM==&quot;hidraw&quot;, KERNELS==&quot;*057E:2007*&quot;, MODE=&quot;0666&quot;
</pre>
<p></p>
<p>&nbsp;</p>
<hr />
<h3><a name="asmdef-files" id="asmdef-files"></a>Using asmdef files with Rewired</h3>
<p>The asmdef system in Unity 2017.3 allows you make script files compile into their own assembly. This is an advanced topic and should not be attempted without thorough knowledge of the asmdef system.</p>
<p>Rewired does not support asmdef files out of the box. You
will have to manage everything with regards to asmdef files. You have to be very knowledgeable about asmdef files and
assembly references to plan the structure. There is no &quot;right&quot; way to organize it. Every organization scheme has its own advantages and
disadvantages.</p>
<p>Rewired contains DLLs and separate script files, both runtime and editor.
You have to manage the asm def files to make sure all the scripts get
included in the correct assembly and that they have references to the
Rewired DLL's that they need (runtime and/or editor).</p>
<p> <strong>Warnings:</strong></p>
<ul>
<li>DO NOT move the Rewired_Core.dll file out of its current location. This
file is used as an anchor allowing Rewired to locate its install folder
location in the editor.</li>
<li> Do not move other files and folders around inside the Rewired installation unless you are
prepared to manually manage all upgrades to Rewired including all upgrades
to added extras, integration packs, addons, etc. installed by Rewired. Rewired relies on its internal folder structure to know where to extract addon packs when installing or upgrading them.</li>
</ul>
<p><strong>One example asmdef structure:</strong></p>
<p>Under
/Rewired/:<br />
|-- Rewired_CSharp.asmdef</p>
<ul>
<li> The primary asmdef file. This .asmdef file will compile all C# scripts under the Rewired folder into Rewired_CSharp.dll.</li>
<li>.asmdef file must be set to compile on all platforms.</li>
</ul>
<p>Under /Rewired/Internal/Scripts/Editor/:<br />
|-- Rewired_CSharp_Editor.asmdef</p>
<ul>
<li>.asmdef file will compile the default editor C# scripts to
Rewired_CSharp_Editor.dll.</li>
<li>.asmdef file must be set to compile only in the Editor.</li>
<li>.asmdef file must have a reference to Rewired_CSharp.asmdef.</li>
</ul>
<p>Every addon pack installed that includes editor scripts must have an additional
Rewired_PACKNAME_CSharp_Editor.asmdef file added to the Editor folder in that pack which
references Rewired_CSharp.asmdef and Rewired_CSharp_Editor.asmdef.</p>
<p>Example, under /Rewired/Extras/ControlMapper/Scripts/Editor/:<br />
|-- Rewired_ControlMapper_CSharp_Editor.asmdef</p>
<ul>
<li>.asmdef file must have a reference to Rewired_CSharp.asmdef.</li>
</ul>
<p> <strong>Disadvantages to this approach:</strong></p>
<ul>
<li>Each addon-pack will add an additional assembly to your project. Tests by
others have shown that the more assemblies the project has, the longer it
will take to compile.</li>
</ul>
<p><strong>Disadvantages to using asmdef files:</strong></p>
<ul>
<li>Any 3rd party asset that depends on a Rewired integration pack or other addon will have
to also be added to an asmdef and a reference added to the Rewired_CSharp
assembly.<br />
</li>
</ul>
<p><br />
</p>
<div class="bottom-pager clearfix">
<a class="back-button" href="Documentation.html" title="Documentation"><span class="button-img"></span>Documentation</a>
</div>
<!-- InstanceEndEditable -->
</div>
</div>
<div class="footer clearfix">
<p class="left">Copyright &copy;2014-2021 <a href="http://guavaman.com" title="Guavaman Enterprises">Guavaman Enterprises</a>. All rights reserved. No materials may be reproduced without permission.</p>
<p class="right"><a href="http://guavaman.com/projects/rewired" title="Return to Rewired Website">Return to Rewired Website</a></p>
</div>
<!-- end .content --></div>
<!-- end .container --></div>
</body>
<!-- InstanceEnd --></html>