InputFieldEnterSubmit.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /// Credit Vicente Russo
  2. /// Sourced from - https://bitbucket.org/SimonDarksideJ/unity-ui-extensions/issues/23/returnkeytriggersbutton
  3. using UnityEngine.Events;
  4. namespace UnityEngine.UI.Extensions
  5. {
  6. /// <summary>
  7. /// Usage: Add this component to the input and add the function to execute to the EnterSubmit event of this script
  8. /// </summary>
  9. [RequireComponent(typeof(InputField))]
  10. [AddComponentMenu("UI/Extensions/Input Field Submit")]
  11. public class InputFieldEnterSubmit : MonoBehaviour
  12. {
  13. [System.Serializable]
  14. public class EnterSubmitEvent : UnityEvent<string>
  15. {
  16. }
  17. public EnterSubmitEvent EnterSubmit;
  18. public bool defocusInput = true;
  19. private InputField _input;
  20. void Awake()
  21. {
  22. _input = GetComponent<InputField>();
  23. _input.onEndEdit.AddListener(OnEndEdit);
  24. }
  25. public void OnEndEdit(string txt)
  26. {
  27. if (!UIExtensionsInputManager.GetKeyDown(KeyCode.Return) && !UIExtensionsInputManager.GetKeyDown(KeyCode.KeypadEnter))
  28. return;
  29. EnterSubmit.Invoke(txt);
  30. if (defocusInput)
  31. {
  32. UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject(null);
  33. }
  34. }
  35. }
  36. }