using AX.MessageSystem; using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using UnityEngine.UI; using AX.InputSystem; public class UINameItem : MonoBehaviour { private Canvas MainCanvas; private RectTransform MyRect; public GameObject Target; public Vector3 offest = Vector3.zero; [HideInInspector] public long ID; private bool Show; public void OnDestroy() { MessageDispatcher.RemoveListener("CHANGE_HEAD_NAME", ChangeHeadName);//改变头顶名称 MessageDispatcher.RemoveListener("CONTROL_HIDE_SHOW_HEAD_NAME", ControlHideShowHeadName);//控制隐藏物体时候显隐名称 MessageDispatcher.RemoveListener("ONDESROY_HEAD_NAME", OnDestroyName);//控制有名称的物体被销毁时候销毁名称 } public void Awake() { MessageDispatcher.AddListener("CHANGE_HEAD_NAME", ChangeHeadName);//改变头顶名称 MessageDispatcher.AddListener("CONTROL_HIDE_SHOW_HEAD_NAME", ControlHideShowHeadName);//控制隐藏物体时候显隐名称 MessageDispatcher.AddListener("ONDESROY_HEAD_NAME", OnDestroyName);//控制有名称的物体被销毁时候销毁名称 } private void OnDestroyName(IMessage obj) { DestroyUINameCmdArgs arg = (DestroyUINameCmdArgs)obj.Data; if (ID == arg.gameObjID) Destroy(gameObject); } private void ControlHideShowHeadName(IMessage obj) { HideShowUINameCmdArgs arg = (HideShowUINameCmdArgs)obj.Data; //if (ID == arg.gameObjID) // Show = arg.IsHide; if (Target.activeSelf) Show = !arg.IsHide; if (!gameObject.activeSelf && Show) gameObject.SetActive(true); } private void SingleHideShowHeadName(IMessage obj) { HideShowUINameCmdArgs arg = (HideShowUINameCmdArgs)obj.Data; if (ID != arg.gameObjID) return; if (Target.activeSelf) Show = !arg.IsHide; if (!gameObject.activeSelf && Show) gameObject.SetActive(true); } private void ChangeHeadName(IMessage obj) { ChangeUINameCmdArgs arg = (ChangeUINameCmdArgs)obj.Data; if (ID == arg.gameObjID) GetComponent().text = arg.Value; } void Start() { MainCanvas = GameObject.Find("Canvas").GetComponent(); MyRect = GetComponent(); ID = Target.GetComponent().gameObjID; } // Update is called once per frame void Update() { if (Target == null) { Destroy(gameObject); } else { if (Show) { if (!IsInView(Target.transform.position)) { MyRect.transform.position = new Vector2(10000, 10000); return; } Vector3 point = Target.transform.position + offest; Vector3 Targetscreenpos = Camera.main.WorldToScreenPoint(point); Vector3 viewpos = GameObject.Find("UICamera").GetComponent().ScreenToWorldPoint(Targetscreenpos); viewpos.z = 0; MyRect.transform.position = viewpos; } else { if (gameObject.activeSelf) gameObject.SetActive(false); } } } public bool IsInView(Vector3 worldPos) { Transform camTransform = Camera.main.transform; Vector2 viewPos = Camera.main.WorldToViewportPoint(worldPos); Vector3 dir = (worldPos - camTransform.position).normalized; float dot = Vector3.Dot(camTransform.forward, dir);//判断物体是否在相机前面 if (dot > 0 && viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1) return true; else return false; } }