关于鼠标拾取代码,点击物体可显示所点击物体名称
***************************************************************************
将下面的javascript代码挂在任何一个对象上面均可以实现,当鼠标点击时打印鼠标所点击的对象的名称
function Update () { if (Input.GetMouseButton (0)) { var ray = Camera.main.ScreenPointToRay (Input.mousePosition); var hit : RaycastHit; if (Physics.Raycast (ray, hit)) { Debug.DrawLine (ray.origin, hit.point); print(hit.collider.gameObject.name); } } }
************************************************************************
代码会有些不同
转换成c#代码如下
首先定义 public RaycastHit hit;
if (Input.GetMouseButton (0)) { var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
****************************************************************
Assets/scripts/SelectTarget.cs(26,21): error CS1502: The best overloaded method match for `UnityEngine.Physics.Raycast(UnityEngine.Ray, out UnityEngine.RaycastHit)' has some invalid arguments
Assets/scripts/SelectTarget.cs(26,21): error CS1620: Argument `#2' is missing `out' modifier
**************************************************************** if (Physics.Raycast (ray, out hit)) //注意这个地方与javascript不同,需要加OUT不然会报错,错误如******之间的提示 { Debug.DrawLine (ray.origin, hit.point); } if(hit.collider.gameObject.name=="所要点击的物体名称") { Debug.Log("选中了"+hit.collider.gameObject.name);
// *************执行什么操作代码放这即可
*************************比如让选中的物体颜色变为红色
GameObject b = Gameobject.Find(hit.collider.gameObject.name);
b.renderer.material.color = Color.red; //比如将颜色变为红色 } }