A
A
Alexey2015-12-28 21:06:40
Unity
Alexey, 2015-12-28 21:06:40

How to get the component of an object received by raycast?

There is the following code:

private void Attack()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(new Vector2(Input.mousePosition.x, Input.mousePosition.y));
        RaycastHit _hit;
        if (Physics.Raycast(ray, out _hit))
        {
            if (_hit.collider.tag == "tree")
            {
                Hp tt = _hit.GetComponent("Hp") as Hp;
                if (tt != null)
                {
                    tt._curHealth -= 1;
                }
                Debug.Log("Этот объект с тэгом tree");
            }
        }
    }
}

Question: why can't I get the component from _hit? Maybe I'm doing something wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2015-12-29
@Alexeee

RaycastHit is a struct that does not have a GetComponent method. RaycastHit.transform has such a method :

private void Attack()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(new Vector2(Input.mousePosition.x, Input.mousePosition.y));
        RaycastHit _hit;
        if (Physics.Raycast(ray, out _hit))
        {
            if (_hit.collider.tag == "tree")
            {
                Hp tt = _hit.transform.GetComponent<Hp>();
                if (tt != null)
                {
                    tt._curHealth -= 1;
                }
                Debug.Log("Этот объект с тэгом tree");
            }
        }
    }
}

And don't use GetComponent with a string argument, use the generic method like above, otherwise your code will break if you decide to rename the class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question