NGUIFollowGameObject.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.SceneManagement;
  4. public class NGUIFollowGameObject : MonoBehaviour
  5. {
  6. private void OnEnable()
  7. {
  8. SceneManager.sceneUnloaded += this.SceneUnloaded;
  9. this.UpdatePosition();
  10. }
  11. private void Update()
  12. {
  13. this.UpdatePosition();
  14. }
  15. private void OnDisable()
  16. {
  17. SceneManager.sceneUnloaded -= this.SceneUnloaded;
  18. }
  19. private void SceneUnloaded(Scene arg0)
  20. {
  21. UnityEngine.Object.Destroy(this);
  22. }
  23. private void UpdatePosition()
  24. {
  25. if (this.open)
  26. {
  27. if (!base.gameObject.activeSelf)
  28. {
  29. base.gameObject.SetActive(true);
  30. }
  31. if (this.isFollow)
  32. {
  33. if (this.gameObj != null)
  34. {
  35. this.followedPos = this.gameObj.position;
  36. }
  37. Vector3 pos = R.Camera.Camera.WorldToViewportPoint(this.followedPos + this.offset);
  38. if (UICamera.mainCamera != null)
  39. {
  40. this.position = this.UIViewportToWorldPoint(pos);
  41. }
  42. }
  43. base.transform.position = this.position;
  44. }
  45. }
  46. public void SetFollowTransform(Transform followed, bool _open = true)
  47. {
  48. this.gameObj = followed;
  49. Vector3 pos = Camera.main.WorldToViewportPoint(this.followedPos);
  50. if (UICamera.mainCamera != null)
  51. {
  52. this.position = this.UIViewportToWorldPoint(pos);
  53. }
  54. this.open = _open;
  55. this.isFollow = true;
  56. }
  57. public void SetFollowTransform(Transform followed, Vector2 offset, bool _open = true)
  58. {
  59. this.offset = offset;
  60. this.SetFollowTransform(followed, _open);
  61. }
  62. public void SetViewPosition(Vector2 pos, bool _open = true)
  63. {
  64. this.gameObj = null;
  65. this.position = this.UIViewportToWorldPoint(pos);
  66. this.open = _open;
  67. this.isFollow = false;
  68. }
  69. public void SetWorldPosition(Vector3 pos, bool follow = true, bool open = true)
  70. {
  71. this.gameObj = null;
  72. Vector3 pos2 = Camera.main.WorldToViewportPoint(pos);
  73. this.position = this.UIViewportToWorldPoint(pos2);
  74. this.open = open;
  75. this.isFollow = follow;
  76. this.followedPos = pos;
  77. }
  78. private Vector3 UIViewportToWorldPoint(Vector3 pos)
  79. {
  80. pos.z = 5f;
  81. return UICamera.mainCamera.ViewportToWorldPoint(pos);
  82. }
  83. public Transform gameObj;
  84. [HideInInspector]
  85. public Vector3 offset = Vector3.zero;
  86. public bool open;
  87. public bool isFollow = true;
  88. [HideInInspector]
  89. public Vector3 position;
  90. private Vector3 followedPos;
  91. }