从 RaycastHit 获取游戏对象
本文关键字:对象 游戏 获取 RaycastHit | 更新日期: 2023-09-27 17:57:13
我正在使用此代码,但不幸的是我收到此错误:
CS1061:键入
UnityEngine.RaycastHit' does not contain a definition for
gameObject',找不到gameObject' of type
UnityEngine.RaycastHit'的扩展方法(是否缺少使用指令或程序集引用?
public float Selected;
public GameObject[] handler;
public float[] prices;
public GameObject Tile;
private Money mon;
// Use this for initialization
void Start () {
mon = GameObject.Find ("Gamelogic").GetComponent<Money>();
}
// Update is called once per frame
void Update () {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast (ray,out hit, 20))
{
if(hit.transform.tag == "tiles")
{
Tile = hit.gameObject;
}
else
{
Tile = null;
}
}
if(Input.GetMouseButtonDown(0) && Tile != null)
{
}
}
}
这是我
使用的一个函数,您应该能够轻松适应它。
GameObject GetClickedGameObject()
{
// Builds a ray from camera point of view to the mouse position
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
// Casts the ray and get the first game object hit
if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
{
Instantiate (clickMarker,hit.point,Quaternion.identity); //places clickMarker at hit.point. This isn't needed, just there for visualisation.
return hit.transform.gameObject;
}
else
return null;
}
我认为你的基本问题是
Tile = hit.gameObject;
需要
Tile = hit.transform.gameObject;
也:
if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
注意这种方式,它有一个内置的layerMask,所以你不需要做你的if(hit.transform.tag == "tiles")
更容易和更短,你总是可以只做:
hit.collider.gameObject.name
这将返回您击中的对象的名牌。然后,您可以执行逻辑检查以及要对该信息执行的任何操作。
更多文档在这里:
https://forum.unity.com/threads/getting-object-hit-with-raycast.573982/