Created
November 27, 2021 18:53
-
-
Save Vanawy/90a2af51734995cdfc982bdb3318d664 to your computer and use it in GitHub Desktop.
Last active device Unity https://forum.unity.com/threads/detect-most-recent-input-device-type.753206/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
using UnityEngine.InputSystem; | |
using UnityEngine.InputSystem.Users; | |
// add this into built-in button you can create from menu: UI/Button | |
public class InputDeviceChangeHandler : MonoBehaviour { | |
// refs to Button's components | |
private Image buttonImage; | |
// refs to your sprites | |
public Sprite gamepadImage; | |
public Sprite keyboardImage; | |
void Awake() { | |
buttonImage = GetComponent<Image>(); | |
PlayerInput input = FindObjectOfType<PlayerInput>(); | |
updateButtonImage(input.currentControlScheme); | |
} | |
void OnEnable() { | |
InputUser.onChange += onInputDeviceChange; | |
} | |
void OnDisable() { | |
InputUser.onChange -= onInputDeviceChange; | |
} | |
void onInputDeviceChange(InputUser user, InputUserChange change, InputDevice device) { | |
if (change == InputUserChange.ControlSchemeChanged) { | |
updateButtonImage(user.controlScheme.Value.name); | |
} | |
} | |
void updateButtonImage(string schemeName) { | |
// assuming you have only 2 schemes: keyboard and gamepad | |
if (schemeName.Equals("Gamepad")) { | |
buttonImage.sprite = gamepadImage; | |
} | |
else { | |
buttonImage.sprite = keyboardImage; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment