WebGLInputMobile.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5. using System.Runtime.InteropServices; // for DllImport
  6. using AOT;
  7. using System;
  8. namespace WebGLSupport
  9. {
  10. class WebGLInputMobilePlugin
  11. {
  12. #if UNITY_WEBGL && !UNITY_EDITOR
  13. [DllImport("__Internal")]
  14. public static extern int WebGLInputMobileRegister(Action<int> OnTouchEnd);
  15. [DllImport("__Internal")]
  16. public static extern void WebGLInputMobileOnFocusOut(int id, Action<int> OnFocusOut);
  17. #else
  18. /// <summary>
  19. /// ID を割り振り
  20. /// </summary>
  21. /// <returns></returns>
  22. public static int WebGLInputMobileRegister(Action<int> OnTouchEnd) { return 0; }
  23. public static void WebGLInputMobileOnFocusOut(int id, Action<int> OnFocusOut) { }
  24. #endif
  25. }
  26. public class WebGLInputMobile : MonoBehaviour, IPointerDownHandler
  27. {
  28. static Dictionary<int, WebGLInputMobile> instances = new Dictionary<int, WebGLInputMobile>();
  29. int id = -1;
  30. private void Awake()
  31. {
  32. #if !(UNITY_WEBGL && !UNITY_EDITOR)
  33. // WebGL 以外、更新メソッドは動作しないようにします
  34. enabled = false;
  35. #endif
  36. }
  37. /// <summary>
  38. /// 押されたら、touchend イベントを登録する
  39. /// </summary>
  40. /// <param name="eventData"></param>
  41. public void OnPointerDown(PointerEventData eventData)
  42. {
  43. if (id != -1) return;
  44. id = WebGLInputMobilePlugin.WebGLInputMobileRegister(OnTouchEnd);
  45. instances[id] = this;
  46. }
  47. [MonoPInvokeCallback(typeof(Action<int>))]
  48. static void OnTouchEnd(int id)
  49. {
  50. var @this = instances[id];
  51. @this.GetComponent<WebGLInput>().OnSelect();
  52. @this.StartCoroutine(RegisterOnFocusOut(id));
  53. }
  54. static IEnumerator RegisterOnFocusOut(int id)
  55. {
  56. yield return null; // wait one frame.
  57. WebGLInputMobilePlugin.WebGLInputMobileOnFocusOut(id, OnFocusOut);
  58. }
  59. [MonoPInvokeCallback(typeof(Action<int>))]
  60. static void OnFocusOut(int id)
  61. {
  62. var @this = instances[id];
  63. @this.StartCoroutine(ExecFocusOut(id));
  64. }
  65. static IEnumerator ExecFocusOut(int id)
  66. {
  67. yield return null; // wait one frame.
  68. var @this = instances[id];
  69. @this.GetComponent<WebGLInput>().DeactivateInputField();
  70. // release
  71. @this.id = -1;
  72. instances.Remove(id);
  73. }
  74. }
  75. }