之前一直用NGUI HUD Text插件做這個功能,感覺一個小功能就導一個插件進來簡直喪心病狂。然后就自己寫了一個~
Camera cam;//用於發射射線的相機 Camera UIcam;//UI層的相機 Vector3 mp;//鼠標位置 Transform targetTransform;//點選的物體 public UILabel Lab; void Start () { cam =this.GetComponent<Camera>(); UIcam = GameObject.Find("Camera").GetComponent<Camera>(); Lab = GameObject.Find("Label").GetComponent<UILabel>(); } void Update() { if (TarRaycast()) //判斷鼠標是否指在某物體上 { //這里轉換坐標的時候我用的是“指定物體y軸方向向上0.3f處”,當然只是大體保證了匹配位置,最好的方式是手動指定,即提前手動拖一個空物體至“有需要點擊的物體”下,固定其合適位置,然后坐標用這個空物體的~ Vector3 pos = cam.WorldToViewportPoint(targetTransform.position + new Vector3(0, targetTransform.localScale.y / 2 + 0.3f, 0)); Lab.transform.position = UIcam.ViewportToWorldPoint(pos); Lab.text = targetTransform.name; } } //射線檢測部分,不懂可看我之前的文章~ public bool TarRaycast() { Lab.text = null; mp = Input.mousePosition; targetTransform = null; if (cam != null) { RaycastHit hitInfo; Ray ray = cam.ScreenPointToRay(new Vector3(mp.x, mp.y, 0f)); if (Physics.Raycast(ray.origin, ray.direction, out hitInfo)) { targetTransform = hitInfo.collider.transform; return true; } } return false; } }