Skip to content

Instantly share code, notes, and snippets.

@Vanawy
Created November 27, 2021 18:53
Show Gist options
  • Save Vanawy/90a2af51734995cdfc982bdb3318d664 to your computer and use it in GitHub Desktop.
Save Vanawy/90a2af51734995cdfc982bdb3318d664 to your computer and use it in GitHub Desktop.
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