从RaycastHit获取游戏对象

时间:2015-06-20 22:01:35

标签: c# unity3d unityscript

我正在使用此代码,但不幸的是我收到此错误:

  

CS1061:输入UnityEngine.RaycastHit' does not contain a definition for gameObject'并且找不到扩展方法gameObject' of type UnityEngine.RaycastHit'(您是否缺少using指令或程序集引用?

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)
    {

    }
  }
}

2 个答案:

答案 0 :(得分:2)

继承我使用的功能,你应该能够轻松地适应它。

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 ==&#34; tiles&#34;)

答案 1 :(得分:0)

更简单、更短,你总是可以这样做:

hit.collider.gameObject.name

它将返回您命中的对象的名称标签。 然后,您可以进行逻辑检查以及您想对这些信息执行的任何操作。

此处有更多文档:

https://forum.unity.com/threads/getting-object-hit-with-raycast.573982/