File size: 90,963 Bytes
18a519f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 | using System;
using System.Collections.Generic;
using UnityEngine.Events;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.InputSystem.Users;
using UnityEngine.InputSystem.Utilities;
#if PACKAGE_DOCS_GENERATION || UNITY_INPUT_SYSTEM_ENABLE_UI
using UnityEngine.InputSystem.UI;
#endif
////TODO: add support for keeping a player's InputUser alive and reconnecting back to it
////TODO: when joining is *off*, allow auto-switching even in multiplayer
////TODO: differentiate not only by already paired devices but rather take control schemes into account; allow two players to be on the same
//// device as long as they are using different control schemes
////TODO: allow PlayerInput to be set up in a way where it's in an unpaired/non-functional state and expects additional configuration
////REVIEW: callback behaviors have been very confusing for users; simplify&clarify this
////REVIEW: having everything coupled to component enable/disable is quite restrictive; can we allow PlayerInputs
//// to be disabled without them leaving the game? would help when wanting to keep players around in the background
//// and only temporarily disable them
////TODO: add support for "continuous" callbacks
////TODO: add event for control scheme switches
////TODO: add ability to name players
////TODO: refresh caches when asset is modified at runtime
////TODO: handle required actions ahead of time so that we catch it if a device matches by type but doesn't otherwise
////TODO: handle case of control scheme not having any devices in its requirements
////TODO: add method to pass an object implementing a generated action interface (IXXXActions) and have it hooked up automatically
//// (or maybe look for implementation on components in same object?)
////TODO: warn if control schemes have no device requirements
////FIXME: why can't I join with a mouse left click?
namespace UnityEngine.InputSystem
{
/// <summary>
/// Represents a separate player in the game complete with a set of actions exclusive
/// to the player and a set of paired device.
/// </summary>
/// <remarks>
/// PlayerInput is a high-level wrapper around much of the input system's functionality
/// which is meant to help getting set up with the new input system quickly. It takes
/// care of <see cref="InputAction"/> bookkeeping and has a custom UI(requires the "Unity UI" package) to help
/// setting up input.
///
/// The component supports local multiplayer implicitly. Each PlayerInput instance
/// represents a distinct user with its own set of devices and actions. To orchestrate
/// player management and facilitate mechanics such as joining by device activity, use
/// <see cref="UnityEngine.InputSystem.PlayerInputManager"/>.
///
/// The way PlayerInput notifies script code of events is determined by <see cref="notificationBehavior"/>.
/// By default, this is set to <see cref="UnityEngine.InputSystem.PlayerNotifications.SendMessages"/> which will use
/// <see cref="GameObject.SendMessage(string,object)"/> to send messages to the <see cref="GameObject"/>
/// that PlayerInput sits on.
///
/// <example>
/// <code>
/// // Component to sit next to PlayerInput.
/// [RequireComponent(typeof(PlayerInput))]
/// public class MyPlayerLogic : MonoBehaviour
/// {
/// public GameObject projectilePrefab;
///
/// private Vector2 m_Look;
/// private Vector2 m_Move;
/// private bool m_Fire;
///
/// // 'Fire' input action has been triggered. For 'Fire' we want continuous
/// // action (that is, firing) while the fire button is held such that the action
/// // gets triggered repeatedly while the button is down. We can easily set this
/// // up by having a "Press" interaction on the button and setting it to repeat
/// // at fixed intervals.
/// public void OnFire()
/// {
/// Instantiate(projectilePrefab);
/// }
///
/// // 'Move' input action has been triggered.
/// public void OnMove(InputValue value)
/// {
/// m_Move = value.Get<Vector2>();
/// }
///
/// // 'Look' input action has been triggered.
/// public void OnLook(InputValue value)
/// {
/// m_Look = value.Get<Vector2>();
/// }
///
/// public void OnUpdate()
/// {
/// // Update transform from m_Move and m_Look
/// }
/// }
/// </code>
/// </example>
///
/// It is also possible to use the polling API of <see cref="InputAction"/>s (see
/// <see cref="InputAction.triggered"/> and <see cref="InputAction.ReadValue{TValue}"/>)
/// in combination with PlayerInput.
///
/// <example>
/// <code>
/// // Component to sit next to PlayerInput.
/// [RequireComponent(typeof(PlayerInput))]
/// public class MyPlayerLogic : MonoBehaviour
/// {
/// public GameObject projectilePrefab;
///
/// private PlayerInput m_PlayerInput;
/// private InputAction m_LookAction;
/// private InputAction m_MoveAction;
/// private InputAction m_FireAction;
///
/// public void OnUpdate()
/// {
/// // First update we look up all the data we need.
/// // NOTE: We don't do this in OnEnable as PlayerInput itself performing some
/// // initialization work in OnEnable.
/// if (m_PlayerInput == null)
/// {
/// m_PlayerInput = GetComponent<PlayerInput>();
/// m_FireAction = m_PlayerInput.actions["fire"];
/// m_LookAction = m_PlayerInput.actions["look"];
/// m_MoveAction = m_PlayerInput.actions["move"];
/// }
///
/// if (m_FireAction.triggered)
/// /* firing logic... */;
///
/// var move = m_MoveAction.ReadValue<Vector2>();
/// var look = m_LookAction.ReadValue<Vector2>();
/// /* Update transform from move&look... */
/// }
/// }
/// </code>
/// </example>
///
/// When enabled, PlayerInput will create an <see cref="InputUser"/> and pair devices to the
/// user which are then specific to the player. The set of devices can be controlled explicitly
/// when instantiating a PlayerInput through <see cref="Instantiate(GameObject,int,string,int,InputDevice[])"/>
/// or <see cref="Instantiate(GameObject,int,string,int,InputDevice)"/>. This also makes it possible
/// to assign the same device to two different players, e.g. for split-keyboard play.
///
/// <example>
/// <code>
/// var p1 = PlayerInput.Instantiate(playerPrefab,
/// controlScheme: "KeyboardLeft", device: Keyboard.current);
/// var p2 = PlayerInput.Instantiate(playerPrefab,
/// controlScheme: "KeyboardRight", device: Keyboard.current);
/// </code>
/// </example>
///
/// If no specific devices are given to a PlayerInput, the component will look for compatible
/// devices present in the system and pair them to itself automatically. If the PlayerInput's
/// <see cref="actions"/> have control schemes defined for them, PlayerInput will look for a
/// control scheme for which all required devices are available and not paired to any other player.
/// It will try <see cref="defaultControlScheme"/> first (if set), but then fall back to trying
/// all available schemes in order. Once a scheme is found for which all required devices are
/// available, PlayerInput will pair those devices to itself and select the given scheme.
///
/// If no control schemes are defined, PlayerInput will try to bind as many as-of-yet unpaired
/// devices to itself as it can match to bindings present in the <see cref="actions"/>. This means
/// that if, for example, there's binding for both keyboard and gamepad and there is one keyboard
/// and two gamepads available when PlayerInput is enabled, all three devices will be paired to
/// the player.
///
/// Note that when using <see cref="PlayerInputManager"/>, device pairing to players is controlled
/// from the joining logic. In that case, PlayerInput will automatically pair the device from which
/// the player joined. If control schemes are present in <see cref="actions"/>, the first one compatible
/// with that device is chosen. If additional devices are required, these will be paired from the pool
/// of currently unpaired devices.
///
/// Device pairings can be changed at any time by either manually controlling pairing through
/// <see cref="InputUser.PerformPairingWithDevice"/> (and related methods) using a PlayerInput's
/// assigned <see cref="user"/> or by switching control schemes (e.g. using
/// <see cref="SwitchCurrentControlScheme(string,InputDevice[])"/>), if any are present in the PlayerInput's
/// <see cref="actions"/>.
///
/// When a player loses a device paired to it (e.g. when it is unplugged or loses power), <see cref="InputUser"/>
/// will signal <see cref="InputUserChange.DeviceLost"/> which is also surfaced as a message,
/// <see cref="deviceLostEvent"/>, or <see cref="onDeviceLost"/> (depending on <see cref="notificationBehavior"/>).
/// When a device is reconnected, <see cref="InputUser"/> will signal <see cref="InputUserChange.DeviceRegained"/>
/// which also is surfaced as a message, as <see cref="deviceRegainedEvent"/>, or <see cref="onDeviceRegained"/>
/// (depending on <see cref="notificationBehavior"/>).
///
/// When there is only a single active PlayerInput in the game, joining is not enabled (see
/// <see cref="PlayerInputManager.joiningEnabled"/>), and <see cref="neverAutoSwitchControlSchemes"/> is not
/// set to <c>true</c>, device pairings for the player will also update automatically based on device usage.
///
/// If control schemes are present in <see cref="actions"/>, then if a device is used (not merely plugged in
/// but rather receives input on a non-noisy, non-synthetic control) which is compatible with a control scheme
/// other than the currently used one, PlayerInput will attempt to switch to that control scheme. Success depends
/// on whether all device requirements for that scheme are met from the set of available devices. If a control
/// scheme happens, <see cref="InputUser"/> signals <see cref="InputUserChange.ControlSchemeChanged"/> on
/// <see cref="InputUser.onChange"/>.
///
/// If no control schemes are present in <see cref="actions"/>, PlayerInput will automatically pair any newly
/// available device to itself if the given device has any bindings available for it.
///
/// Both behaviors described in the previous two paragraphs are automatically disabled if more than one
/// PlayerInput is active.
/// </remarks>
/// <seealso cref="UnityEngine.InputSystem.PlayerInputManager"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
[AddComponentMenu("Input/Player Input")]
[DisallowMultipleComponent]
[HelpURL(InputSystem.kDocUrl + "/manual/PlayerInput.html")]
public class PlayerInput : MonoBehaviour
{
/// <summary>
/// Name of the message that is sent with <c>UnityEngine.Object.SendMessage</c> when a
/// player loses a device.
/// </summary>
/// <seealso cref="onDeviceLost"/>
public const string DeviceLostMessage = "OnDeviceLost";
/// <summary>
/// Name of the message that is sent with <c>UnityEngine.Object.SendMessage</c> when a
/// player regains a device.
/// </summary>
/// <seealso cref="onDeviceRegained"/>
public const string DeviceRegainedMessage = "OnDeviceRegained";
/// <summary>
/// Name of the message that is sent with <c>UnityEngine.Object.SendMessage</c> when the
/// controls used by a player are changed.
/// </summary>
/// <seealso cref="onControlsChanged"/>
public const string ControlsChangedMessage = "OnControlsChanged";
/// <summary>
/// Whether input is on the player is active.
/// </summary>
/// <value>If true, the player is receiving input.</value>
/// <seealso cref="ActivateInput"/>
/// <seealso cref="DeactivateInput"/>
public bool inputIsActive => m_InputActive;
[Obsolete("Use inputIsActive instead.")]
public bool active => inputIsActive;
/// <summary>
/// Unique, zero-based index of the player. For example, <c>2</c> for the third player.
/// </summary>
/// <value>Unique index of the player.</value>
/// <remarks>
/// Once assigned, a player index will not change.
///
/// Note that the player index does not necessarily correspond to the player's index in <see cref="all"/>.
/// The array will always contain all currently enabled players so when a player is disabled or destroyed,
/// it will be removed from the array. However, the player index of the remaining players will not change.
/// </remarks>
public int playerIndex => m_PlayerIndex;
/// <summary>
/// If split-screen is enabled (<see cref="UnityEngine.InputSystem.PlayerInputManager.splitScreen"/>),
/// this is the index of the screen area used by the player.
/// </summary>
/// <value>Index of split-screen area assigned to player or -1 if the player is not
/// using split-screen.</value>
/// <remarks>
/// Split screen areas are enumerated row by row and within rows, column by column. So, if, for example,
/// there are four separate split-screen areas, the upper left one is #0, the upper right one is #1,
/// the lower left one is #2, and the lower right one is #3.
///
/// Split screen areas are usually assigned automatically but players can also be assigned to
/// areas explicitly through <see cref="Instantiate(GameObject,int,string,int,InputDevice)"/> or
/// <see cref="PlayerInputManager.JoinPlayer(int,int,string,InputDevice)"/>.
/// </remarks>
/// <seealso cref="camera"/>
/// <seealso cref="PlayerInputManager.splitScreen"/>
public int splitScreenIndex => m_SplitScreenIndex;
/// <summary>
/// Input actions associated with the player.
/// </summary>
/// <value>Asset holding the player's input actions.</value>
/// <remarks>
/// Note that every player will maintain a unique copy of the given actions such that
/// each player receives an identical copy. When assigning the same actions to multiple players,
/// the first player will use the given actions as is but any subsequent player will make a copy
/// of the actions using <see cref="Object.Instantiate(Object)"/>.
///
/// The asset may contain an arbitrary number of action maps. By setting <see cref="defaultActionMap"/>,
/// one of them can be selected to enabled automatically when PlayerInput is enabled. If no default
/// action map is selected, none of the action maps will be enabled by PlayerInput itself. Use
/// <see cref="SwitchCurrentActionMap"/> or just call <see cref="InputActionMap.Enable"/> directly
/// to enable a specific map.
///
/// Notifications will be sent for all actions in the asset, not just for those in the first action
/// map. This means that if additional maps are manually enabled and disabled, notifications will
/// be sent for their actions as they receive input.
/// </remarks>
/// <seealso cref="InputUser.actions"/>
/// <seealso cref="SwitchCurrentActionMap"/>
public InputActionAsset actions
{
get
{
if (!m_ActionsInitialized && gameObject.activeInHierarchy)
InitializeActions();
return m_Actions;
}
set
{
if (m_Actions == value)
return;
// Make sure that if we already have actions, they get disabled.
if (m_Actions != null)
{
m_Actions.Disable();
if (m_ActionsInitialized)
UninitializeActions();
}
m_Actions = value;
if (m_Enabled)
{
ClearCaches();
AssignUserAndDevices();
InitializeActions();
if (m_InputActive)
ActivateInput();
}
}
}
/// <summary>
/// Name of the currently active control scheme.
/// </summary>
/// <value>Name of the currently active control scheme or <c>null</c>.</value>
/// <remarks>
/// Note that this property will be <c>null</c> if there are no control schemes
/// defined in <see cref="actions"/>.
/// </remarks>
/// <seealso cref="SwitchCurrentControlScheme(UnityEngine.InputSystem.InputDevice[])"/>
/// <seealso cref="defaultControlScheme"/>
/// <seealso cref="InputActionAsset.controlSchemes"/>
public string currentControlScheme
{
get
{
if (!m_InputUser.valid)
return null;
var scheme = m_InputUser.controlScheme;
return scheme?.name;
}
}
/// <summary>
/// The default control scheme to try.
/// </summary>
/// <value>Name of the default control scheme.</value>
/// <remarks>
/// When PlayerInput is enabled and this is not <c>null</c> and not empty, the PlayerInput
/// will look up the control scheme in <see cref="InputActionAsset.controlSchemes"/> of
/// <see cref="actions"/>. If found, PlayerInput will try to activate the scheme. This will
/// succeed only if all devices required by the control scheme are either already paired to
/// the player or are available as devices not used by other PlayerInputs.
///
/// Note that this property only determines the first control scheme to try. If using the
/// control scheme fails, PlayerInput will fall back to trying the other control schemes
/// (if any) available from <see cref="actions"/>.
/// </remarks>
/// <seealso cref="SwitchCurrentControlScheme(InputDevice[])"/>
/// <seealso cref="currentControlScheme"/>
public string defaultControlScheme
{
get => m_DefaultControlScheme;
set => m_DefaultControlScheme = value;
}
/// <summary>
/// If true, do not automatically switch control schemes even when there is only a single player.
/// By default, this property is false.
/// </summary>
/// <value>If true, do not switch control schemes when other devices are used.</value>
/// <remarks>
/// By default, when there is only a single PlayerInput enabled, we assume that the game is in
/// single-player mode and that the player should be able to freely switch between the control schemes
/// supported by the game. For example, if the player is currently using mouse and keyboard, but is
/// then switching to a gamepad, PlayerInput should automatically switch to the control scheme for
/// gamepads, if present.
///
/// When there is more than one PlayerInput or when joining is enabled <see cref="PlayerInputManager"/>,
/// this behavior is automatically turned off as we wouldn't know which player is switching if a
/// currently unpaired device is used.
///
/// By setting this property to true, auto-switching of control schemes is forcibly turned off and
/// will thus not be performed even if there is only a single PlayerInput in the game.
///
/// Note that you can still switch control schemes manually using <see
/// cref="SwitchCurrentControlScheme(string,InputDevice[])"/>.
/// </remarks>
/// <seealso cref="currentControlScheme"/>
/// <seealso cref="isSinglePlayer"/>
public bool neverAutoSwitchControlSchemes
{
get => m_NeverAutoSwitchControlSchemes;
set
{
if (m_NeverAutoSwitchControlSchemes == value)
return;
m_NeverAutoSwitchControlSchemes = value;
if (m_Enabled)
{
if (!value && !m_OnUnpairedDeviceUsedHooked)
StartListeningForUnpairedDeviceActivity();
else if (value && m_OnUnpairedDeviceUsedHooked)
StopListeningForUnpairedDeviceActivity();
}
}
}
////REVIEW: this is inconsistent; currentControlScheme is a string, this is an InputActionMap
/// <summary>
/// The currently enabled action map.
/// </summary>
/// <value>Reference to the currently enabled action or <c>null</c> if no action
/// map has been enabled by PlayerInput.</value>
/// <remarks>
/// Note that the concept of "current action map" is local to PlayerInput. You can still freely
/// enable and disable action maps directly on the <see cref="actions"/> asset. This property
/// only tracks which action map has been enabled under the control of PlayerInput, i.e. either
/// by means of <see cref="defaultActionMap"/> or by using <see cref="SwitchCurrentActionMap"/>.
/// </remarks>
/// <seealso cref="SwitchCurrentActionMap"/>
public InputActionMap currentActionMap
{
get => m_CurrentActionMap;
set
{
// If someone switches maps from an action callback, we may get here recursively
// from Disable(). To avoid that, we null out the current action map while
// we disable it.
var oldMap = m_CurrentActionMap;
m_CurrentActionMap = null;
oldMap?.Disable();
// Switch to new map.
m_CurrentActionMap = value;
m_CurrentActionMap?.Enable();
}
}
/// <summary>
/// Name (see <see cref="InputActionMap.name"/>) or ID (see <see cref="InputActionMap.id"/>) of the action
/// map to enable by default.
/// </summary>
/// <value>Action map to enable by default or <c>null</c>.</value>
/// <remarks>
/// By default, when enabled, PlayerInput will not enable any of the actions in the <see cref="actions"/>
/// asset. By setting this property, however, PlayerInput can be made to automatically enable the respective
/// action map.
/// </remarks>
/// <seealso cref="currentActionMap"/>
/// <seealso cref="SwitchCurrentActionMap"/>
public string defaultActionMap
{
get => m_DefaultActionMap;
set => m_DefaultActionMap = value;
}
/// <summary>
/// Determines how the component notifies listeners about input actions and other input-related
/// events pertaining to the player.
/// </summary>
/// <value>How to trigger notifications on events.</value>
/// <remarks>
/// By default, the component will use <see cref="GameObject.SendMessage(string,object)"/> to send messages
/// to the <see cref="GameObject"/>. This can be changed by selecting a different <see cref="UnityEngine.InputSystem.PlayerNotifications"/>
/// behavior.
/// </remarks>
/// <seealso cref="actionEvents"/>
/// <seealso cref="deviceLostEvent"/>
/// <seealso cref="deviceRegainedEvent"/>
public PlayerNotifications notificationBehavior
{
get => m_NotificationBehavior;
set
{
if (m_NotificationBehavior == value)
return;
if (m_Enabled)
UninitializeActions();
m_NotificationBehavior = value;
if (m_Enabled)
InitializeActions();
}
}
/// <summary>
/// List of events invoked in response to actions being triggered.
/// </summary>
/// <remarks>
/// This array is only used if <see cref="notificationBehavior"/> is set to
/// <see cref="UnityEngine.InputSystem.PlayerNotifications.InvokeUnityEvents"/>.
/// </remarks>
public ReadOnlyArray<ActionEvent> actionEvents
{
get => m_ActionEvents;
set
{
if (m_Enabled)
UninitializeActions();
m_ActionEvents = value.ToArray();
if (m_Enabled)
InitializeActions();
}
}
/// <summary>
/// Event that is triggered when the player loses a device (e.g. the batteries run out).
/// </summary>
/// <remarks>
/// This event is only used if <see cref="notificationBehavior"/> is set to
/// <see cref="UnityEngine.InputSystem.PlayerNotifications.InvokeUnityEvents"/>.
/// </remarks>
public DeviceLostEvent deviceLostEvent
{
get
{
if (m_DeviceLostEvent == null)
m_DeviceLostEvent = new DeviceLostEvent();
return m_DeviceLostEvent;
}
}
/// <summary>
/// Event that is triggered when the player recovers from device loss and is good to go again.
/// </summary>
/// <remarks>
/// This event is only used if <see cref="notificationBehavior"/> is set to
/// <see cref="UnityEngine.InputSystem.PlayerNotifications.InvokeUnityEvents"/>.
/// </remarks>
public DeviceRegainedEvent deviceRegainedEvent
{
get
{
if (m_DeviceRegainedEvent == null)
m_DeviceRegainedEvent = new DeviceRegainedEvent();
return m_DeviceRegainedEvent;
}
}
/// <summary>
/// Event that is triggered when the controls used by the player change.
/// </summary>
/// <remarks>
/// This event is only used if <see cref="notificationBehavior"/> is set to
/// <see cref="UnityEngine.InputSystem.PlayerNotifications.InvokeUnityEvents"/>.
///
/// The event is trigger when the set of <see cref="devices"/> used by the player change,
/// when the player switches to a different control scheme (see <see cref="currentControlScheme"/>),
/// or when the bindings used by the player are changed (e.g. when rebinding them). Also,
/// for <see cref="Keyboard"/> devices, the event is triggered when the currently used
/// keyboard layout (see <see cref="Keyboard.keyboardLayout"/>) changes.
/// </remarks>
public ControlsChangedEvent controlsChangedEvent
{
get
{
if (m_ControlsChangedEvent == null)
m_ControlsChangedEvent = new ControlsChangedEvent();
return m_ControlsChangedEvent;
}
}
/// <summary>
/// If <see cref="notificationBehavior"/> is set to <see cref="PlayerNotifications.InvokeCSharpEvents"/>, this
/// event is triggered when an action fires.
/// </summary>
/// <value>Callbacks that get called when an action triggers.</value>
/// <remarks>
/// If <see cref="notificationBehavior"/> is not set to <see cref="PlayerNotifications.InvokeCSharpEvents"/>, the
/// value of this property is ignored.
///
/// The callbacks are called in sync (and with the same argument) with <see cref="InputAction.started"/>,
/// <see cref="InputAction.performed"/>, and <see cref="InputAction.canceled"/>.
/// </remarks>
/// <seealso cref="InputActionMap.actionTriggered"/>
/// <seealso cref="InputAction.started"/>
/// <seealso cref="InputAction.performed"/>
/// <seealso cref="InputAction.canceled"/>
/// <seealso cref="actions"/>
public event Action<InputAction.CallbackContext> onActionTriggered
{
add
{
if (value == null)
throw new ArgumentNullException(nameof(value));
m_ActionTriggeredCallbacks.AddCallback(value);
}
remove
{
if (value == null)
throw new ArgumentNullException(nameof(value));
m_ActionTriggeredCallbacks.RemoveCallback(value);
}
}
/// <summary>
/// If <see cref="notificationBehavior"/> is <see cref="PlayerNotifications.InvokeCSharpEvents"/>, this event
/// is triggered when a device paired to the player is disconnected.
/// </summary>
/// <value>Callbacks that get called when the player loses a device.</value>
/// <remarks>
/// If <see cref="notificationBehavior"/> is not <see cref="PlayerNotifications.InvokeCSharpEvents"/>, the value
/// of this property is ignored.
///
/// The argument is the player that lost its device (i.e. the player on which the callback is installed).
/// </remarks>
/// <seealso cref="onDeviceRegained"/>
/// <seealso cref="InputUserChange.DeviceLost"/>
public event Action<PlayerInput> onDeviceLost
{
add
{
if (value == null)
throw new ArgumentNullException(nameof(value));
m_DeviceLostCallbacks.AddCallback(value);
}
remove
{
if (value == null)
throw new ArgumentNullException(nameof(value));
m_DeviceLostCallbacks.RemoveCallback(value);
}
}
/// <summary>
/// If <see cref="notificationBehavior"/> is <see cref="PlayerNotifications.InvokeCSharpEvents"/>, this event
/// is triggered when the player previously lost a device and has now regained it or an equivalent device.
/// </summary>
/// <value>Callbacks that get called when the player regains a device.</value>
/// <remarks>
/// If <see cref="notificationBehavior"/> is not <see cref="PlayerNotifications.InvokeCSharpEvents"/>, the value
/// of this property is ignored.
///
/// The argument is the player that regained a device (i.e. the player on which the callback is installed).
/// </remarks>
/// <seealso cref="onDeviceLost"/>
/// <seealso cref="InputUserChange.DeviceRegained"/>
public event Action<PlayerInput> onDeviceRegained
{
add
{
if (value == null)
throw new ArgumentNullException(nameof(value));
m_DeviceRegainedCallbacks.AddCallback(value);
}
remove
{
if (value == null)
throw new ArgumentNullException(nameof(value));
m_DeviceRegainedCallbacks.RemoveCallback(value);
}
}
/// <summary>
/// If <see cref="notificationBehavior"/> is <see cref="PlayerNotifications.InvokeCSharpEvents"/>, this event
/// is triggered when the controls used by the players are changed.
/// </summary>
/// <remarks>
/// The callback is invoked when the set of <see cref="devices"/> used by the player change,
/// when the player switches to a different control scheme (see <see cref="currentControlScheme"/>),
/// or when the bindings used by the player are changed (e.g. when rebinding them). Also,
/// for <see cref="Keyboard"/> devices, the callback is invoked when the currently used
/// keyboard layout (see <see cref="Keyboard.keyboardLayout"/>) changes.
/// </remarks>
public event Action<PlayerInput> onControlsChanged
{
add
{
if (value == null)
throw new ArgumentNullException(nameof(value));
m_ControlsChangedCallbacks.AddCallback(value);
}
remove
{
if (value == null)
throw new ArgumentNullException(nameof(value));
m_ControlsChangedCallbacks.RemoveCallback(value);
}
}
////TODO: clarify the relationship to raycasting in the UI input module
/// <summary>
/// Optional camera associated with the player.
/// </summary>
/// <value>Camera specific to the player or <c>null</c>.</value>
/// <remarks>
/// This is <c>null</c> by default.
///
/// Associating a camera with a player is necessary only when using split-screen (see <see cref="PlayerInputManager.splitScreen"/>).
/// </remarks>
public
#if UNITY_EDITOR
// camera property is deprecated and only available in Editor.
new
#endif
Camera camera
{
get => m_Camera;
set => m_Camera = value;
}
#if PACKAGE_DOCS_GENERATION || UNITY_INPUT_SYSTEM_ENABLE_UI
/// <summary>
/// UI InputModule that should have it's input actions synchronized to this PlayerInput's actions.
/// </summary>
public InputSystemUIInputModule uiInputModule
{
get => m_UIInputModule;
set
{
if (m_UIInputModule == value)
return;
if (m_UIInputModule != null && m_UIInputModule.actionsAsset == m_Actions)
m_UIInputModule.actionsAsset = null;
m_UIInputModule = value;
if (m_UIInputModule != null && m_Actions != null)
m_UIInputModule.actionsAsset = m_Actions;
}
}
#endif
/// <summary>
/// The internal user tied to the player.
/// </summary>
public InputUser user => m_InputUser;
/// <summary>
/// The devices paired to the player.
/// </summary>
/// <value>List of devices paired to player.</value>
/// <remarks>
/// </remarks>
/// <seealso cref="InputUser.pairedDevices"/>
public ReadOnlyArray<InputDevice> devices
{
get
{
if (!m_InputUser.valid)
return new ReadOnlyArray<InputDevice>();
return m_InputUser.pairedDevices;
}
}
/// <summary>
/// Whether the player is missed required devices. This means that the player's
/// input setup is probably at least partially non-functional.
/// </summary>
/// <value>True if the player is missing devices required by the control scheme.</value>
/// <remarks>
/// This can happen, for example, if the a device is unplugged during the game.
/// </remarks>
/// <seealso cref="InputControlScheme.deviceRequirements"/>
/// <seealso cref="InputUser.hasMissingRequiredDevices"/>
public bool hasMissingRequiredDevices => user.valid && user.hasMissingRequiredDevices;
/// <summary>
/// List of all players that are currently joined. Sorted by <see cref="playerIndex"/> in
/// increasing order.
/// </summary>
/// <value>List of active PlayerInputs.</value>
/// <remarks>
/// While the list is sorted by <see cref="playerIndex"/>, note that this does not mean that the <see cref="playerIndex"/>
/// of a player corresponds to the index in this list. If, for example, three players join and then the second player leaves,
/// the list will contain one player with <see cref="playerIndex"/> 0 followed by one player with <see cref="playerIndex"/> 2.
/// </remarks>
/// <seealso cref="PlayerInputManager.JoinPlayer(int,int,string,InputDevice)"/>
/// <seealso cref="Instantiate(GameObject,int,string,int,InputDevice)"/>
public static ReadOnlyArray<PlayerInput> all => new ReadOnlyArray<PlayerInput>(s_AllActivePlayers, 0, s_AllActivePlayersCount);
/// <summary>
/// Whether PlayerInput operates in single-player mode.
/// </summary>
/// <value>If true, there is at most a single PlayerInput.</value>
/// <remarks>
/// Single-player mode is active while there is at most one PlayerInput (there can also be none) and
/// while joining is not enabled in <see cref="PlayerInputManager"/> (if one exists). See <see cref="PlayerInputManager.joiningEnabled"/>.
///
/// Automatic control scheme switching (if enabled) is predicated on single-player mode being active.
/// </remarks>
/// <seealso cref="neverAutoSwitchControlSchemes"/>
public static bool isSinglePlayer =>
s_AllActivePlayersCount <= 1 &&
(PlayerInputManager.instance == null || !PlayerInputManager.instance.joiningEnabled);
/// <summary>
/// Return the first device of the given type from <see cref="devices"/> paired to the player.
/// If no device of this type is paired to the player, return <c>null</c>.
/// </summary>
/// <typeparam name="TDevice">Type of device to look for (such as <see cref="Mouse"/>). Can be a supertype
/// of the actual device type. For example, querying for <see cref="Pointer"/>, may return a <see cref="Mouse"/>.</typeparam>
/// <returns>The first device paired to the player that is of the given type or <c>null</c> if the player
/// does not have a matching device.</returns>
/// <seealso cref="devices"/>
public TDevice GetDevice<TDevice>()
where TDevice : InputDevice
{
foreach (var device in devices)
if (device is TDevice deviceOfType)
return deviceOfType;
return null;
}
/// <summary>
/// Enable input on the player.
/// </summary>
/// <remarks>
/// Input will automatically be activated when the PlayerInput component is enabled. However, this method
/// can be called to reactivate input after deactivating it with <see cref="DeactivateInput"/>.
///
/// Note that activating input will activate the current action map only (see <see cref="currentActionMap"/>).
/// </remarks>
/// <see cref="inputIsActive"/>
/// <seealso cref="DeactivateInput"/>
public void ActivateInput()
{
m_InputActive = true;
// If we have no current action map but there's a default
// action map, make it current.
if (m_CurrentActionMap == null && m_Actions != null && !string.IsNullOrEmpty(m_DefaultActionMap))
SwitchCurrentActionMap(m_DefaultActionMap);
else
m_CurrentActionMap?.Enable();
}
/// <summary>
/// Disable input on the player.
/// </summary>
/// <remarks>
/// Input is automatically activated when the PlayerInput component is enabled. This method can be
/// used to deactivate input manually.
///
/// Note that activating input will deactivate the current action map only (see <see cref="currentActionMap"/>).
/// </remarks>
/// <see cref="ActivateInput"/>
/// <see cref="inputIsActive"/>
public void DeactivateInput()
{
m_CurrentActionMap?.Disable();
m_InputActive = false;
}
[Obsolete("Use DeactivateInput instead.")]
public void PassivateInput()
{
DeactivateInput();
}
/// <summary>
/// Switch the current control scheme to one that fits the given set of devices.
/// </summary>
/// <param name="devices">A list of input devices. Note that if any of the devices is already paired to another
/// player, the device will end up paired to both players.</param>
/// <returns>True if the switch was successful, false otherwise. The latter can happen, for example, if
/// <see cref="actions"/> does not have a control scheme that fits the given set of devices.</returns>
/// <exception cref="ArgumentNullException"><paramref name="devices"/> is <c>null</c>.</exception>
/// <exception cref="InvalidOperationException"><see cref="actions"/> has not been assigned.</exception>
/// <remarks>
/// The player's currently paired devices (see <see cref="devices"/>) will get unpaired.
///
/// <example>
/// <code>
/// // Switch the first player to keyboard and mouse.
/// PlayerInput.all[0]
/// .SwitchCurrentControlScheme(Keyboard.current, Mouse.current);
/// </code>
/// </example>
/// </remarks>
/// <seealso cref="currentControlScheme"/>
/// <seealso cref="InputActionAsset.controlSchemes"/>
public bool SwitchCurrentControlScheme(params InputDevice[] devices)
{
if (devices == null)
throw new ArgumentNullException(nameof(devices));
if (actions == null)
throw new InvalidOperationException(
"Must set actions on PlayerInput in order to be able to switch control schemes");
// Find control scheme matching given devices in associated action asset
var scheme = InputControlScheme.FindControlSchemeForDevices(devices, actions.controlSchemes);
if (!scheme.HasValue)
return false;
var controlScheme = scheme.Value;
SwitchControlSchemeInternal(ref controlScheme, devices);
return true;
}
////REVIEW: these should just be SwitchControlScheme
/// <summary>
/// Switch the player to use the given control scheme together with the given devices.
/// </summary>
/// <param name="controlScheme">Name of the control scheme. See <see cref="InputControlScheme.name"/>.</param>
/// <param name="devices">A list of devices.</param>
/// <exception cref="ArgumentNullException"><paramref name="devices"/> is <c>null</c> -or- <paramref name="controlScheme"/> is
/// <c>null</c> or empty.</exception>
/// <remarks>
/// This method can be used to explicitly force a combination of control scheme and a specific set of
/// devices.
///
/// <example>
/// <code>
/// // Put player 1 on the "Gamepad" control scheme together
/// // with the second gamepad.
/// PlayerInput.all[0].SwitchControlScheme(
/// "Gamepad",
/// Gamepad.all[1]);
/// </code>
/// </example>
///
/// The player's currently paired devices (see <see cref="devices"/>) will get unpaired.
/// </remarks>
/// <seealso cref="InputActionAsset.controlSchemes"/>
/// <seealso cref="currentControlScheme"/>
public void SwitchCurrentControlScheme(string controlScheme, params InputDevice[] devices)
{
if (string.IsNullOrEmpty(controlScheme))
throw new ArgumentNullException(nameof(controlScheme));
if (devices == null)
throw new ArgumentNullException(nameof(devices));
user.FindControlScheme(controlScheme, out InputControlScheme scheme); // throws if not found
SwitchControlSchemeInternal(ref scheme, devices);
}
public void SwitchCurrentActionMap(string mapNameOrId)
{
// Must be enabled.
if (!m_Enabled)
{
Debug.LogError($"Cannot switch to actions '{mapNameOrId}'; input is not enabled", this);
return;
}
// Must have actions.
if (m_Actions == null)
{
Debug.LogError($"Cannot switch to actions '{mapNameOrId}'; no actions set on PlayerInput", this);
return;
}
// Must have map.
var actionMap = m_Actions.FindActionMap(mapNameOrId);
if (actionMap == null)
{
Debug.LogError($"Cannot find action map '{mapNameOrId}' in actions '{m_Actions}'", this);
return;
}
currentActionMap = actionMap;
}
/// <summary>
/// Return the Nth player.
/// </summary>
/// <param name="playerIndex">Index of the player to return.</param>
/// <returns>The player with the given player index or <c>null</c> if no such
/// player exists.</returns>
/// <seealso cref="PlayerInput.playerIndex"/>
public static PlayerInput GetPlayerByIndex(int playerIndex)
{
for (var i = 0; i < s_AllActivePlayersCount; ++i)
if (s_AllActivePlayers[i].playerIndex == playerIndex)
return s_AllActivePlayers[i];
return null;
}
/// <summary>
/// Find the first PlayerInput who the given device is paired to.
/// </summary>
/// <param name="device">An input device.</param>
/// <returns>The player who is paired to the given device or <c>null</c> if no
/// PlayerInput currently is paired to <paramref name="device"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="device"/> is <c>null</c>.</exception>
/// <remarks>
/// <example>
/// <code>
/// // Find the player paired to first gamepad.
/// var player = PlayerInput.FindFirstPairedToDevice(Gamepad.all[0]);
/// </code>
/// </example>
/// </remarks>
public static PlayerInput FindFirstPairedToDevice(InputDevice device)
{
if (device == null)
throw new ArgumentNullException(nameof(device));
for (var i = 0; i < s_AllActivePlayersCount; ++i)
{
if (ReadOnlyArrayExtensions.ContainsReference(s_AllActivePlayers[i].devices, device))
return s_AllActivePlayers[i];
}
return null;
}
/// <summary>
/// Instantiate a player object and set up and enable its inputs.
/// </summary>
/// <param name="prefab">Prefab to clone. Must contain a PlayerInput component somewhere in its hierarchy.</param>
/// <param name="playerIndex">Player index to assign to the player. See <see cref="PlayerInput.playerIndex"/>.
/// By default will be assigned automatically based on how many players are in <see cref="all"/>.</param>
/// <param name="controlScheme">Control scheme to activate</param>
/// <param name="splitScreenIndex"></param>
/// <param name="pairWithDevice">Device to pair to the user. By default, this is <c>null</c> which means
/// that PlayerInput will automatically pair with available, unpaired devices based on the control schemes (if any)
/// present in <see cref="actions"/> or on the bindings therein (if no control schemes are present).</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"><paramref name="prefab"/> is <c>null</c>.</exception>
public static PlayerInput Instantiate(GameObject prefab, int playerIndex = -1, string controlScheme = null,
int splitScreenIndex = -1, InputDevice pairWithDevice = null)
{
if (prefab == null)
throw new ArgumentNullException(nameof(prefab));
// Set initialization data.
s_InitPlayerIndex = playerIndex;
s_InitSplitScreenIndex = splitScreenIndex;
s_InitControlScheme = controlScheme;
if (pairWithDevice != null)
ArrayHelpers.AppendWithCapacity(ref s_InitPairWithDevices, ref s_InitPairWithDevicesCount, pairWithDevice);
return DoInstantiate(prefab);
}
////TODO: allow instantiating with an existing InputUser
/// <summary>
/// A wrapper around <see cref="Object.Instantiate(Object)"/> that allows instantiating a player prefab and
/// automatically pair one or more specific devices to the newly created player.
/// </summary>
/// <param name="prefab">A player prefab containing a <see cref="PlayerInput"/> component in its hierarchy.</param>
/// <param name="playerIndex"></param>
/// <param name="controlScheme"></param>
/// <param name="splitScreenIndex"></param>
/// <param name="pairWithDevices"></param>
/// <returns></returns>
/// <remarks>
/// Note that unlike <see cref="Object.Instantiate(Object)"/>, this method will always activate the resulting
/// <see cref="GameObject"/> and its components.
/// </remarks>
public static PlayerInput Instantiate(GameObject prefab, int playerIndex = -1, string controlScheme = null,
int splitScreenIndex = -1, params InputDevice[] pairWithDevices)
{
if (prefab == null)
throw new ArgumentNullException(nameof(prefab));
// Set initialization data.
s_InitPlayerIndex = playerIndex;
s_InitSplitScreenIndex = splitScreenIndex;
s_InitControlScheme = controlScheme;
if (pairWithDevices != null)
{
for (var i = 0; i < pairWithDevices.Length; ++i)
ArrayHelpers.AppendWithCapacity(ref s_InitPairWithDevices, ref s_InitPairWithDevicesCount, pairWithDevices[i]);
}
return DoInstantiate(prefab);
}
private static PlayerInput DoInstantiate(GameObject prefab)
{
var destroyIfDeviceSetupUnsuccessful = s_DestroyIfDeviceSetupUnsuccessful;
GameObject instance;
try
{
instance = Object.Instantiate(prefab);
instance.SetActive(true);
}
finally
{
// Reset init data.
s_InitPairWithDevicesCount = 0;
if (s_InitPairWithDevices != null)
Array.Clear(s_InitPairWithDevices, 0, s_InitPairWithDevicesCount);
s_InitControlScheme = null;
s_InitPlayerIndex = -1;
s_InitSplitScreenIndex = -1;
s_DestroyIfDeviceSetupUnsuccessful = false;
}
var playerInput = instance.GetComponentInChildren<PlayerInput>();
if (playerInput == null)
{
DestroyImmediate(instance);
Debug.LogError("The GameObject does not have a PlayerInput component", prefab);
return null;
}
if (destroyIfDeviceSetupUnsuccessful && (!playerInput.user.valid || playerInput.hasMissingRequiredDevices))
{
DestroyImmediate(instance);
return null;
}
return playerInput;
}
[Tooltip("Input actions associated with the player.")]
[SerializeField] internal InputActionAsset m_Actions;
[Tooltip("Determine how notifications should be sent when an input-related event associated with the player happens.")]
[SerializeField] internal PlayerNotifications m_NotificationBehavior;
[Tooltip("UI InputModule that should have it's input actions synchronized to this PlayerInput's actions.")]
#if UNITY_INPUT_SYSTEM_ENABLE_UI
[SerializeField] internal InputSystemUIInputModule m_UIInputModule;
[Tooltip("Event that is triggered when the PlayerInput loses a paired device (e.g. its battery runs out).")]
#endif
[SerializeField] internal DeviceLostEvent m_DeviceLostEvent;
[SerializeField] internal DeviceRegainedEvent m_DeviceRegainedEvent;
[SerializeField] internal ControlsChangedEvent m_ControlsChangedEvent;
[SerializeField] internal ActionEvent[] m_ActionEvents;
[SerializeField] internal bool m_NeverAutoSwitchControlSchemes;
[SerializeField] internal string m_DefaultControlScheme;////REVIEW: should we have IDs for these so we can rename safely?
[SerializeField] internal string m_DefaultActionMap;
[SerializeField] internal int m_SplitScreenIndex = -1;
[Tooltip("Reference to the player's view camera. Note that this is only required when using split-screen and/or "
+ "per-player UIs. Otherwise it is safe to leave this property uninitialized.")]
[SerializeField] internal Camera m_Camera;
// Value object we use when sending messages via SendMessage() or BroadcastMessage(). Can be ignored
// by the receiver. We reuse the same object over and over to avoid allocating garbage.
[NonSerialized] private InputValue m_InputValueObject;
[NonSerialized] internal InputActionMap m_CurrentActionMap;
[NonSerialized] private int m_PlayerIndex = -1;
[NonSerialized] private bool m_InputActive;
[NonSerialized] private bool m_Enabled;
[NonSerialized] internal bool m_ActionsInitialized;
[NonSerialized] private Dictionary<string, string> m_ActionMessageNames;
[NonSerialized] private InputUser m_InputUser;
[NonSerialized] private Action<InputAction.CallbackContext> m_ActionTriggeredDelegate;
[NonSerialized] private CallbackArray<Action<PlayerInput>> m_DeviceLostCallbacks;
[NonSerialized] private CallbackArray<Action<PlayerInput>> m_DeviceRegainedCallbacks;
[NonSerialized] private CallbackArray<Action<PlayerInput>> m_ControlsChangedCallbacks;
[NonSerialized] private CallbackArray<Action<InputAction.CallbackContext>> m_ActionTriggeredCallbacks;
[NonSerialized] private Action<InputControl, InputEventPtr> m_UnpairedDeviceUsedDelegate;
[NonSerialized] private Func<InputDevice, InputEventPtr, bool> m_PreFilterUnpairedDeviceUsedDelegate;
[NonSerialized] private bool m_OnUnpairedDeviceUsedHooked;
[NonSerialized] private Action<InputDevice, InputDeviceChange> m_DeviceChangeDelegate;
[NonSerialized] private bool m_OnDeviceChangeHooked;
internal static int s_AllActivePlayersCount;
internal static PlayerInput[] s_AllActivePlayers;
private static Action<InputUser, InputUserChange, InputDevice> s_UserChangeDelegate;
// The following information is used when the next PlayerInput component is enabled.
private static int s_InitPairWithDevicesCount;
private static InputDevice[] s_InitPairWithDevices;
private static int s_InitPlayerIndex = -1;
private static int s_InitSplitScreenIndex = -1;
private static string s_InitControlScheme;
internal static bool s_DestroyIfDeviceSetupUnsuccessful;
private void InitializeActions()
{
if (m_ActionsInitialized)
return;
if (m_Actions == null)
return;
// Check if we need to duplicate our actions by looking at all other players. If any
// has the same actions, duplicate.
for (var i = 0; i < s_AllActivePlayersCount; ++i)
if (s_AllActivePlayers[i].m_Actions == m_Actions && s_AllActivePlayers[i] != this)
{
var oldActions = m_Actions;
m_Actions = Instantiate(m_Actions);
for (var actionMap = 0; actionMap < oldActions.actionMaps.Count; actionMap++)
{
for (var binding = 0; binding < oldActions.actionMaps[actionMap].bindings.Count; binding++)
m_Actions.actionMaps[actionMap].ApplyBindingOverride(binding, oldActions.actionMaps[actionMap].bindings[binding]);
}
break;
}
#if UNITY_INPUT_SYSTEM_ENABLE_UI
if (uiInputModule != null)
uiInputModule.actionsAsset = m_Actions;
#endif
switch (m_NotificationBehavior)
{
case PlayerNotifications.SendMessages:
case PlayerNotifications.BroadcastMessages:
InstallOnActionTriggeredHook();
if (m_ActionMessageNames == null)
CacheMessageNames();
break;
case PlayerNotifications.InvokeCSharpEvents:
InstallOnActionTriggeredHook();
break;
case PlayerNotifications.InvokeUnityEvents:
{
// Hook up all action events.
if (m_ActionEvents != null)
{
foreach (var actionEvent in m_ActionEvents)
{
var id = actionEvent.actionId;
if (string.IsNullOrEmpty(id))
continue;
// Find action for event.
var action = m_Actions.FindAction(id);
if (action == null)
continue;
action.performed += actionEvent.Invoke;
action.canceled += actionEvent.Invoke;
action.started += actionEvent.Invoke;
}
}
break;
}
}
m_ActionsInitialized = true;
}
private void UninitializeActions()
{
if (!m_ActionsInitialized)
return;
if (m_Actions == null)
return;
UninstallOnActionTriggeredHook();
if (m_NotificationBehavior == PlayerNotifications.InvokeUnityEvents && m_ActionEvents != null)
{
foreach (var actionEvent in m_ActionEvents)
{
var id = actionEvent.actionId;
if (string.IsNullOrEmpty(id))
continue;
// Find action for event.
var action = m_Actions.FindAction(id);
if (action != null)
{
////REVIEW: really wish we had a single callback
action.performed -= actionEvent.Invoke;
action.canceled -= actionEvent.Invoke;
action.started -= actionEvent.Invoke;
}
}
}
m_CurrentActionMap = null;
m_ActionsInitialized = false;
}
private void InstallOnActionTriggeredHook()
{
if (m_ActionTriggeredDelegate == null)
m_ActionTriggeredDelegate = OnActionTriggered;
foreach (var actionMap in m_Actions.actionMaps)
actionMap.actionTriggered += m_ActionTriggeredDelegate;
}
private void UninstallOnActionTriggeredHook()
{
if (m_ActionTriggeredDelegate != null)
foreach (var actionMap in m_Actions.actionMaps)
actionMap.actionTriggered -= m_ActionTriggeredDelegate;
}
private void OnActionTriggered(InputAction.CallbackContext context)
{
if (!m_InputActive)
return;
// We shouldn't go through this method when using UnityEvents. With events,
// the callbacks should be wired up directly rather than going all to this method.
Debug.Assert(m_NotificationBehavior != PlayerNotifications.InvokeUnityEvents,
"OnActionTriggered callback should not be installed if notification behavior is set to InvokeUnityEvents");
switch (m_NotificationBehavior)
{
case PlayerNotifications.InvokeCSharpEvents:
DelegateHelpers.InvokeCallbacksSafe(ref m_ActionTriggeredCallbacks, context, "PlayerInput.onActionTriggered");
break;
case PlayerNotifications.BroadcastMessages:
case PlayerNotifications.SendMessages:
// ATM we only care about `performed` and, in the case of value actions, `canceled`.
var action = context.action;
if (!(context.performed || (context.canceled && action.type == InputActionType.Value)))
return;
// Find message name for action.
if (m_ActionMessageNames == null)
CacheMessageNames();
var messageName = m_ActionMessageNames[action.m_Id];
// Cache value.
if (m_InputValueObject == null)
m_InputValueObject = new InputValue();
m_InputValueObject.m_Context = context;
// Send message.
if (m_NotificationBehavior == PlayerNotifications.BroadcastMessages)
BroadcastMessage(messageName, m_InputValueObject, SendMessageOptions.DontRequireReceiver);
else
SendMessage(messageName, m_InputValueObject, SendMessageOptions.DontRequireReceiver);
// Reset context so calling Get() will result in an exception.
m_InputValueObject.m_Context = null;
break;
}
}
private void CacheMessageNames()
{
if (m_Actions == null)
return;
if (m_ActionMessageNames != null)
m_ActionMessageNames.Clear();
else
m_ActionMessageNames = new Dictionary<string, string>();
foreach (var action in m_Actions)
{
action.MakeSureIdIsInPlace();
var name = CSharpCodeHelpers.MakeTypeName(action.name);
m_ActionMessageNames[action.m_Id] = "On" + name;
}
}
private void ClearCaches()
{
}
/// <summary>
/// Initialize <see cref="user"/> and <see cref="devices"/>.
/// </summary>
private void AssignUserAndDevices()
{
// If we already have a user at this point, clear out all its paired devices
// to start the pairing process from scratch.
if (m_InputUser.valid)
m_InputUser.UnpairDevices();
// All our input goes through actions so there's no point setting
// anything up if we have none.
if (m_Actions == null)
{
// If we have devices we are meant to pair with, do so. Otherwise, don't
// do anything as we don't know what kind of input to look for.
if (s_InitPairWithDevicesCount > 0)
{
for (var i = 0; i < s_InitPairWithDevicesCount; ++i)
m_InputUser = InputUser.PerformPairingWithDevice(s_InitPairWithDevices[i], m_InputUser);
}
else
{
// Make sure user is invalid.
m_InputUser = new InputUser();
}
return;
}
// If we have control schemes, try to find the one we should use.
if (m_Actions.controlSchemes.Count > 0)
{
if (!string.IsNullOrEmpty(s_InitControlScheme))
{
// We've been given a control scheme to initialize this. Try that one and
// that one only. Might mean we end up with missing devices.
var controlScheme = m_Actions.FindControlScheme(s_InitControlScheme);
if (controlScheme == null)
{
Debug.LogError($"No control scheme '{s_InitControlScheme}' in '{m_Actions}'", this);
}
else
{
TryToActivateControlScheme(controlScheme.Value);
}
}
else if (!string.IsNullOrEmpty(m_DefaultControlScheme))
{
// There's a control scheme we should try by default.
var controlScheme = m_Actions.FindControlScheme(m_DefaultControlScheme);
if (controlScheme == null)
{
Debug.LogError($"Cannot find default control scheme '{m_DefaultControlScheme}' in '{m_Actions}'", this);
}
else
{
TryToActivateControlScheme(controlScheme.Value);
}
}
// If we did not end up with a usable scheme by now but we've been given devices to pair with,
// search for a control scheme matching the given devices.
if (s_InitPairWithDevicesCount > 0 && (!m_InputUser.valid || m_InputUser.controlScheme == null))
{
// The devices we've been given may not be all the devices required to satisfy a given control scheme so we
// want to pick any one control scheme that is the best match for the devices we have regardless of whether
// we'll need additional devices. TryToActivateControlScheme will take care of that.
var controlScheme = InputControlScheme.FindControlSchemeForDevices(
new ReadOnlyArray<InputDevice>(s_InitPairWithDevices, 0, s_InitPairWithDevicesCount), m_Actions.controlSchemes,
allowUnsuccesfulMatch: true);
if (controlScheme != null)
TryToActivateControlScheme(controlScheme.Value);
}
// If we don't have a working control scheme by now and we haven't been instructed to use
// one specific control scheme, try each one in the asset one after the other until we
// either find one we can use or run out of options.
else if ((!m_InputUser.valid || m_InputUser.controlScheme == null) && string.IsNullOrEmpty(s_InitControlScheme))
{
using (var availableDevices = InputUser.GetUnpairedInputDevices())
{
var controlScheme = InputControlScheme.FindControlSchemeForDevices(availableDevices, m_Actions.controlSchemes);
if (controlScheme != null)
TryToActivateControlScheme(controlScheme.Value);
}
}
}
else
{
// There's no control schemes in the asset. If we've been given a set of devices,
// we run with those (regardless of whether there's bindings for them in the actions or not).
// If we haven't been given any devices, we go through all bindings in the asset and whatever
// device is present that matches the binding and that isn't used by any other player, we'll
// pair to the player.
if (s_InitPairWithDevicesCount > 0)
{
for (var i = 0; i < s_InitPairWithDevicesCount; ++i)
m_InputUser = InputUser.PerformPairingWithDevice(s_InitPairWithDevices[i], m_InputUser);
}
else
{
// Pair all devices for which we have a binding.
using (var availableDevices = InputUser.GetUnpairedInputDevices())
{
for (var i = 0; i < availableDevices.Count; ++i)
{
var device = availableDevices[i];
if (!HaveBindingForDevice(device))
continue;
m_InputUser = InputUser.PerformPairingWithDevice(device, m_InputUser);
}
}
}
}
// If we don't have a valid user at this point, we don't have any paired devices.
if (m_InputUser.valid)
m_InputUser.AssociateActionsWithUser(m_Actions);
}
private bool HaveBindingForDevice(InputDevice device)
{
if (m_Actions == null)
return false;
var actionMaps = m_Actions.actionMaps;
for (var i = 0; i < actionMaps.Count; ++i)
{
var actionMap = actionMaps[i];
if (actionMap.IsUsableWithDevice(device))
return true;
}
return false;
}
private void UnassignUserAndDevices()
{
if (m_InputUser.valid)
m_InputUser.UnpairDevicesAndRemoveUser();
if (m_Actions != null)
m_Actions.devices = null;
}
private bool TryToActivateControlScheme(InputControlScheme controlScheme)
{
////FIXME: this will fall apart if account management is involved and a user needs to log in on device first
// Pair any devices we may have been given.
if (s_InitPairWithDevicesCount > 0)
{
////REVIEW: should AndPairRemainingDevices() require that there is at least one existing
//// device paired to the user that is usable with the given control scheme?
// First make sure that all of the devices actually work with the given control scheme.
// We're fine having to pair additional devices but we don't want the situation where
// we have the player grab all the devices in s_InitPairWithDevices along with a control
// scheme that fits none of them and then AndPairRemainingDevices() supplying the devices
// actually needed by the control scheme.
for (var i = 0; i < s_InitPairWithDevicesCount; ++i)
{
var device = s_InitPairWithDevices[i];
if (!controlScheme.SupportsDevice(device))
return false;
}
// We're good. Give the devices to the user.
for (var i = 0; i < s_InitPairWithDevicesCount; ++i)
{
var device = s_InitPairWithDevices[i];
m_InputUser = InputUser.PerformPairingWithDevice(device, m_InputUser);
}
}
if (!m_InputUser.valid)
m_InputUser = InputUser.CreateUserWithoutPairedDevices();
m_InputUser.ActivateControlScheme(controlScheme).AndPairRemainingDevices();
if (user.hasMissingRequiredDevices)
{
m_InputUser.ActivateControlScheme(null);
m_InputUser.UnpairDevices();
return false;
}
return true;
}
private void AssignPlayerIndex()
{
if (s_InitPlayerIndex != -1)
m_PlayerIndex = s_InitPlayerIndex;
else
{
var minPlayerIndex = int.MaxValue;
var maxPlayerIndex = int.MinValue;
for (var i = 0; i < s_AllActivePlayersCount; ++i)
{
var playerIndex = s_AllActivePlayers[i].playerIndex;
minPlayerIndex = Math.Min(minPlayerIndex, playerIndex);
maxPlayerIndex = Math.Max(maxPlayerIndex, playerIndex);
}
if (minPlayerIndex != int.MaxValue && minPlayerIndex > 0)
{
// There's an index between 0 and the current minimum available.
m_PlayerIndex = minPlayerIndex - 1;
}
else if (maxPlayerIndex != int.MinValue)
{
// There may be an index between the minimum and maximum available.
// Search the range. If there's nothing, create a new maximum.
for (var i = minPlayerIndex; i < maxPlayerIndex; ++i)
{
if (GetPlayerByIndex(i) == null)
{
m_PlayerIndex = i;
return;
}
}
m_PlayerIndex = maxPlayerIndex + 1;
}
else
m_PlayerIndex = 0;
}
}
private void OnEnable()
{
m_Enabled = true;
using (InputActionRebindingExtensions.DeferBindingResolution())
{
AssignPlayerIndex();
InitializeActions();
AssignUserAndDevices();
ActivateInput();
}
// Split-screen index defaults to player index.
if (s_InitSplitScreenIndex >= 0)
m_SplitScreenIndex = splitScreenIndex;
else
m_SplitScreenIndex = playerIndex;
// Add to global list and sort it by player index.
ArrayHelpers.AppendWithCapacity(ref s_AllActivePlayers, ref s_AllActivePlayersCount, this);
for (var i = 1; i < s_AllActivePlayersCount; ++i)
for (var j = i; j > 0 && s_AllActivePlayers[j - 1].playerIndex > s_AllActivePlayers[j].playerIndex; --j)
s_AllActivePlayers.SwapElements(j, j - 1);
// If it's the first player, hook into user change notifications.
if (s_AllActivePlayersCount == 1)
{
if (s_UserChangeDelegate == null)
s_UserChangeDelegate = OnUserChange;
InputUser.onChange += s_UserChangeDelegate;
}
// In single player, set up for automatic device switching.
if (isSinglePlayer)
{
if (m_Actions != null && m_Actions.controlSchemes.Count == 0)
{
// No control schemes. We pick up whatever is compatible with the bindings
// we have.
StartListeningForDeviceChanges();
}
else if (!neverAutoSwitchControlSchemes)
{
// We have control schemes so we only listen for unpaired device *input*, i.e.
// actual use of an unpaired device (as opposed to it merely getting plugged in).
StartListeningForUnpairedDeviceActivity();
}
}
HandleControlsChanged();
// Trigger join event.
PlayerInputManager.instance?.NotifyPlayerJoined(this);
}
private void StartListeningForUnpairedDeviceActivity()
{
if (m_OnUnpairedDeviceUsedHooked)
return;
if (m_UnpairedDeviceUsedDelegate == null)
m_UnpairedDeviceUsedDelegate = OnUnpairedDeviceUsed;
if (m_PreFilterUnpairedDeviceUsedDelegate == null)
m_PreFilterUnpairedDeviceUsedDelegate = OnPreFilterUnpairedDeviceUsed;
InputUser.onUnpairedDeviceUsed += m_UnpairedDeviceUsedDelegate;
InputUser.onPrefilterUnpairedDeviceActivity += m_PreFilterUnpairedDeviceUsedDelegate;
++InputUser.listenForUnpairedDeviceActivity;
m_OnUnpairedDeviceUsedHooked = true;
}
private void StopListeningForUnpairedDeviceActivity()
{
if (!m_OnUnpairedDeviceUsedHooked)
return;
InputUser.onUnpairedDeviceUsed -= m_UnpairedDeviceUsedDelegate;
InputUser.onPrefilterUnpairedDeviceActivity -= m_PreFilterUnpairedDeviceUsedDelegate;
--InputUser.listenForUnpairedDeviceActivity;
m_OnUnpairedDeviceUsedHooked = false;
}
private void StartListeningForDeviceChanges()
{
if (m_OnDeviceChangeHooked)
return;
if (m_DeviceChangeDelegate == null)
m_DeviceChangeDelegate = OnDeviceChange;
InputSystem.onDeviceChange += m_DeviceChangeDelegate;
m_OnDeviceChangeHooked = true;
}
private void StopListeningForDeviceChanges()
{
if (!m_OnDeviceChangeHooked)
return;
InputSystem.onDeviceChange -= m_DeviceChangeDelegate;
m_OnDeviceChangeHooked = false;
}
private void OnDisable()
{
m_Enabled = false;
// Remove from global list.
var index = ArrayHelpers.IndexOfReference(s_AllActivePlayers, this, s_AllActivePlayersCount);
if (index != -1)
ArrayHelpers.EraseAtWithCapacity(s_AllActivePlayers, ref s_AllActivePlayersCount, index);
// Unhook from change notifications if we're the last player.
if (s_AllActivePlayersCount == 0 && s_UserChangeDelegate != null)
InputUser.onChange -= s_UserChangeDelegate;
StopListeningForUnpairedDeviceActivity();
StopListeningForDeviceChanges();
// Trigger leave event.
PlayerInputManager.instance?.NotifyPlayerLeft(this);
////TODO: ideally, this shouldn't have to resolve at all and instead wait for someone to need the updated setup
// Avoid re-resolving bindings over and over while we disassemble
// the configuration.
using (InputActionRebindingExtensions.DeferBindingResolution())
{
DeactivateInput();
UnassignUserAndDevices();
UninitializeActions();
}
m_PlayerIndex = -1;
}
// ReSharper disable once UnusedMember.Global
/// <summary>
/// Debug helper method that can be hooked up to actions when using <see cref="UnityEngine.InputSystem.PlayerNotifications.InvokeUnityEvents"/>.
/// </summary>
public void DebugLogAction(InputAction.CallbackContext context)
{
Debug.Log(context.ToString());
}
private void HandleDeviceLost()
{
switch (m_NotificationBehavior)
{
case PlayerNotifications.SendMessages:
SendMessage(DeviceLostMessage, this, SendMessageOptions.DontRequireReceiver);
break;
case PlayerNotifications.BroadcastMessages:
BroadcastMessage(DeviceLostMessage, this, SendMessageOptions.DontRequireReceiver);
break;
case PlayerNotifications.InvokeUnityEvents:
m_DeviceLostEvent?.Invoke(this);
break;
case PlayerNotifications.InvokeCSharpEvents:
DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceLostCallbacks, this, "onDeviceLost");
break;
}
}
private void HandleDeviceRegained()
{
switch (m_NotificationBehavior)
{
case PlayerNotifications.SendMessages:
SendMessage(DeviceRegainedMessage, this, SendMessageOptions.DontRequireReceiver);
break;
case PlayerNotifications.BroadcastMessages:
BroadcastMessage(DeviceRegainedMessage, this, SendMessageOptions.DontRequireReceiver);
break;
case PlayerNotifications.InvokeUnityEvents:
m_DeviceRegainedEvent?.Invoke(this);
break;
case PlayerNotifications.InvokeCSharpEvents:
DelegateHelpers.InvokeCallbacksSafe(ref m_DeviceRegainedCallbacks, this, "onDeviceRegained");
break;
}
}
private void HandleControlsChanged()
{
switch (m_NotificationBehavior)
{
case PlayerNotifications.SendMessages:
SendMessage(ControlsChangedMessage, this, SendMessageOptions.DontRequireReceiver);
break;
case PlayerNotifications.BroadcastMessages:
BroadcastMessage(ControlsChangedMessage, this, SendMessageOptions.DontRequireReceiver);
break;
case PlayerNotifications.InvokeUnityEvents:
m_ControlsChangedEvent?.Invoke(this);
break;
case PlayerNotifications.InvokeCSharpEvents:
DelegateHelpers.InvokeCallbacksSafe(ref m_ControlsChangedCallbacks, this, "onControlsChanged");
break;
}
}
private static void OnUserChange(InputUser user, InputUserChange change, InputDevice device)
{
switch (change)
{
case InputUserChange.DeviceLost:
case InputUserChange.DeviceRegained:
for (var i = 0; i < s_AllActivePlayersCount; ++i)
{
var player = s_AllActivePlayers[i];
if (player.m_InputUser == user)
{
if (change == InputUserChange.DeviceLost)
player.HandleDeviceLost();
else if (change == InputUserChange.DeviceRegained)
player.HandleDeviceRegained();
}
}
break;
case InputUserChange.ControlsChanged:
for (var i = 0; i < s_AllActivePlayersCount; ++i)
{
var player = s_AllActivePlayers[i];
if (player.m_InputUser == user)
player.HandleControlsChanged();
}
break;
}
}
private static bool OnPreFilterUnpairedDeviceUsed(InputDevice device, InputEventPtr eventPtr)
{
// Early out if the device isn't usable with any of our control schemes.
var actions = all[0].actions;
return actions != null && actions.IsUsableWithDevice(device);
}
private void OnUnpairedDeviceUsed(InputControl control, InputEventPtr eventPtr)
{
// We only support automatic control scheme switching in single player mode.
// OnEnable() should automatically unhook us.
if (!isSinglePlayer || neverAutoSwitchControlSchemes)
return;
var player = all[0];
var actions = player.m_Actions;
if (actions == null)
return;
var device = control.device;
using (InputActionRebindingExtensions.DeferBindingResolution())
using (var availableDevices = InputUser.GetUnpairedInputDevices())
{
// Put our device first in the list to make sure it's the first one picked for a match.
if (availableDevices.Count > 1)
{
var indexOfDevice = availableDevices.IndexOf(device);
Debug.Assert(indexOfDevice != -1, "Did not find unpaired device in list of unpaired devices");
availableDevices.SwapElements(0, indexOfDevice);
}
// Add all devices currently already paired to us. This avoids us preventing
// control schemes switches because of devices we're looking for already being
// paired to us.
var currentDevices = player.devices;
for (var i = 0; i < currentDevices.Count; ++i)
availableDevices.Add(currentDevices[i]);
// Find the best control scheme to use.
if (InputControlScheme.FindControlSchemeForDevices(availableDevices, player.m_Actions.controlSchemes,
out var controlScheme, out var matchResult, mustIncludeDevice: device))
{
try
{
// First remove the currently paired devices.
var userValid = player.user.valid;
if (userValid)
player.user.UnpairDevices();
// Then pair devices that we've picked according to the control scheme.
var newDevices = matchResult.devices;
Debug.Assert(newDevices.Count > 0, "Expecting to see at least one device here");
for (var i = 0; i < newDevices.Count; ++i)
{
player.m_InputUser = InputUser.PerformPairingWithDevice(newDevices[i], user: player.m_InputUser);
if (!userValid && player.actions != null)
player.m_InputUser.AssociateActionsWithUser(player.actions);
}
// And finally switch to the new control scheme.
player.user.ActivateControlScheme(controlScheme);
}
finally
{
matchResult.Dispose();
}
}
}
}
private void OnDeviceChange(InputDevice device, InputDeviceChange change)
{
// If a device was added and we have no control schemes in the actions and we're in
// single-player mode, pair the device to the player if it works with the bindings we have.
if (change == InputDeviceChange.Added &&
isSinglePlayer &&
m_Actions != null && m_Actions.controlSchemes.Count == 0 &&
HaveBindingForDevice(device) &&
m_InputUser.valid)
{
InputUser.PerformPairingWithDevice(device, user: m_InputUser);
}
}
private void SwitchControlSchemeInternal(ref InputControlScheme controlScheme, params InputDevice[] devices)
{
Debug.Assert(devices != null);
// Note that we are doing two somwhat uncorrelated actions here:
// - Switching control scheme
// - Explicitly pairing with given devices regardless if making sense with respect to control scheme
using (InputActionRebindingExtensions.DeferBindingResolution())
{
// Unpair device previously paired but not part of given devices to pair with
for (var i = user.pairedDevices.Count - 1; i >= 0; --i)
{
if (!devices.ContainsReference(user.pairedDevices[i]))
user.UnpairDevice(user.pairedDevices[i]);
}
// Pair devices not previously paired but that are part of given devices to pair with
foreach (var device in devices)
{
if (!user.pairedDevices.ContainsReference(device))
InputUser.PerformPairingWithDevice(device, user: user);
}
// Only activate control scheme if its a different scheme
if (!user.controlScheme.HasValue || !user.controlScheme.Value.Equals(controlScheme))
user.ActivateControlScheme(controlScheme);
}
}
[Serializable]
public class ActionEvent : UnityEvent<InputAction.CallbackContext>
{
public string actionId => m_ActionId;
public string actionName => m_ActionName;
[SerializeField] private string m_ActionId;
[SerializeField] private string m_ActionName;
public ActionEvent()
{
}
public ActionEvent(InputAction action)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
if (action.isSingletonAction)
throw new ArgumentException($"Action must be part of an asset (given action '{action}' is a singleton)");
if (action.actionMap.asset == null)
throw new ArgumentException($"Action must be part of an asset (given action '{action}' is not)");
m_ActionId = action.id.ToString();
m_ActionName = $"{action.actionMap.name}/{action.name}";
}
public ActionEvent(Guid actionGUID, string name = null)
{
m_ActionId = actionGUID.ToString();
m_ActionName = name;
}
}
/// <summary>
/// Event that is triggered when an <see cref="InputDevice"/> paired to a <see cref="PlayerInput"/> is disconnected.
/// </summary>
/// <seealso cref="deviceLostEvent"/>
[Serializable]
public class DeviceLostEvent : UnityEvent<PlayerInput>
{
}
/// <summary>
/// Event that is triggered when a <see cref="PlayerInput"/> regains an <see cref="InputDevice"/> previously lost.
/// </summary>
/// <seealso cref="deviceRegainedEvent"/>
[Serializable]
public class DeviceRegainedEvent : UnityEvent<PlayerInput>
{
}
/// <summary>
/// Event that is triggered when the set of controls used by a <see cref="PlayerInput"/> changes.
/// </summary>
/// <seealso cref="controlsChangedEvent"/>
[Serializable]
public class ControlsChangedEvent : UnityEvent<PlayerInput>
{
}
}
}
|