--判断血条是否在屏幕中
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; } void Update () { Vector2 vec2 = Camera.main.WorldToScreenPoint (this.gameObject.transform.position); if (IsInView (transform.position)) { rectBloodPos.gameObject.SetActive (true); rectBloodPos.anchoredPosition = new Vector2 (vec2.x - Screen.width / 2 + 0, vec2.y - Screen.height / 2 + 60); } else rectBloodPos.gameObject.SetActive (false); }
第二种:通过monoBehaviour来判断
void OnBecameVisible(){//可见状态下你要执行 的东西}void OnBecameInvisible(){//不可见状态下你要执行的东西}