PanelManager.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.EventSystems;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. public class PanelManager : MonoBehaviour {
  7. public Animator initiallyOpen;
  8. private int m_OpenParameterId;
  9. private Animator m_Open;
  10. private GameObject m_PreviouslySelected;
  11. const string k_OpenTransitionName = "Open";
  12. const string k_ClosedStateName = "Closed";
  13. public void OnEnable()
  14. {
  15. m_OpenParameterId = Animator.StringToHash (k_OpenTransitionName);
  16. if (initiallyOpen == null)
  17. return;
  18. OpenPanel(initiallyOpen);
  19. }
  20. public void OpenPanel (Animator anim)
  21. {
  22. if (m_Open == anim)
  23. return;
  24. anim.gameObject.SetActive(true);
  25. var newPreviouslySelected = EventSystem.current.currentSelectedGameObject;
  26. anim.transform.SetAsLastSibling();
  27. CloseCurrent();
  28. m_PreviouslySelected = newPreviouslySelected;
  29. m_Open = anim;
  30. m_Open.SetBool(m_OpenParameterId, true);
  31. GameObject go = FindFirstEnabledSelectable(anim.gameObject);
  32. SetSelected(go);
  33. }
  34. static GameObject FindFirstEnabledSelectable (GameObject gameObject)
  35. {
  36. GameObject go = null;
  37. var selectables = gameObject.GetComponentsInChildren<Selectable> (true);
  38. foreach (var selectable in selectables) {
  39. if (selectable.IsActive () && selectable.IsInteractable ()) {
  40. go = selectable.gameObject;
  41. break;
  42. }
  43. }
  44. return go;
  45. }
  46. public void CloseCurrent()
  47. {
  48. if (m_Open == null)
  49. return;
  50. m_Open.SetBool(m_OpenParameterId, false);
  51. SetSelected(m_PreviouslySelected);
  52. StartCoroutine(DisablePanelDeleyed(m_Open));
  53. m_Open = null;
  54. }
  55. IEnumerator DisablePanelDeleyed(Animator anim)
  56. {
  57. bool closedStateReached = false;
  58. bool wantToClose = true;
  59. while (!closedStateReached && wantToClose)
  60. {
  61. if (!anim.IsInTransition(0))
  62. closedStateReached = anim.GetCurrentAnimatorStateInfo(0).IsName(k_ClosedStateName);
  63. wantToClose = !anim.GetBool(m_OpenParameterId);
  64. yield return new WaitForEndOfFrame();
  65. }
  66. if (wantToClose)
  67. anim.gameObject.SetActive(false);
  68. }
  69. private void SetSelected(GameObject go)
  70. {
  71. EventSystem.current.SetSelectedGameObject(go);
  72. }
  73. }