Skip to content

Instantly share code, notes, and snippets.

@marinho
Created September 28, 2022 19:55
Show Gist options
  • Save marinho/64aa28b204f8492865d676121287c502 to your computer and use it in GitHub Desktop.
Save marinho/64aa28b204f8492865d676121287c502 to your computer and use it in GitHub Desktop.
Extending SciFi UI PressEventKey to support Unity's New Input System
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
using Michsky.UI.Shift;
public class NeutrinoPressKeyEvent : PressKeyEvent
{
[Header("Input System")]
[SerializeField] NeutrinoInputSystemType inputSystem = NeutrinoInputSystemType.Hotkey;
[SerializeField] InputActionAsset inputActionAsset;
[SerializeField] string inputActionMapName;
[SerializeField] string inputActionName;
[SerializeField] bool ignoreWhenCanvasGroupNotVisible = true;
[SerializeField] float canvasGroupAlphaThreshold = 1f;
InputActionMap inputActionMap;
InputAction inputAction;
CanvasGroup canvasGroup;
void Awake() {
if (inputActionAsset != null && inputActionMapName != "" && inputActionName != "") {
inputActionMap = inputActionAsset.FindActionMap(inputActionMapName, throwIfNotFound: true);
inputAction = inputActionMap.FindAction(inputActionName, throwIfNotFound: true);
inputAction.performed += _ => InputActionPerformed();
// MARIO: for some reason, when home is visible from start, it calls OnEnabled() and OnDisabled() even
// though it's actually active. That's why I keep it enabled and check gameObject.activeInHierarchy
// instead of using the methods to enable or disable inputActionAsset
inputActionAsset?.Enable();
}
canvasGroup = GetComponentInParent<CanvasGroup>();
}
void Update()
{
if (pressAnyKey == true) {
if (Input.anyKeyDown)
ExecuteAction();
} else if (inputSystem == NeutrinoInputSystemType.Hotkey) {
UpdateForHotkey();
}
}
void InputActionPerformed() {
if (inputSystem != NeutrinoInputSystemType.InputAction) {
return;
}
ExecuteAction();
}
void UpdateForHotkey() {
// MARIO: changed from GetKeyDown to GetKeyUp to fix bug that multiple panels are called
if (Input.GetKeyUp(hotkey)) { 
ExecuteAction();
}
}
void ExecuteAction() {
// MARIO: all panels remain active, but hidden just with canvasGroup.alpha = 0, that's why
bool ignoreBecauseNotVisible = ignoreWhenCanvasGroupNotVisible && canvasGroup != null && canvasGroup.alpha < canvasGroupAlphaThreshold;
if (ignoreBecauseNotVisible || !gameObject.activeInHierarchy) {
return;
}
pressAction.Invoke();
}
}
public enum NeutrinoInputSystemType {
Hotkey,
InputAction
}
@marinho
Copy link
Author

marinho commented Sep 28, 2022

This is how it looks like in Unity's inspector tab.

The Hotkey is ignored when Input System is "InputAction" and vice-versa.

Screenshot 2022-09-28 at 21 56 28

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment