Answer the question
In order to leave comments, you need to log in
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");
}
}
}
}
Answer the question
In order to leave comments, you need to log in
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");
}
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question