I want to enable some gameobjects with a raycast.
I have a principal object which cointains a Child with a collider. This Child contains a text which I want to enable when the Child's collider is hit by the raycast. I've tried with the code bellow but doesn't work. How can I access the child with the raycast?
public class SeleccionarTesoro_LIST : MonoBehaviour {
void Start()
{
GameObject[] hitObject = GameObject.FindGameObjectsWithTag("TESOROS");
}
public void SetHitObjectToActive(GameObject hitObject)
{
hitObject.transform.GetChild(0).GetChild(0).gameObject.SetActive (true);
hitObject.transform.GetChild(0).GetChild(2).gameObject.SetActive (true);
}
void Update() {
if (Input.GetMouseButtonDown (0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
SetHitObjectToActive (hit.collider.gameObject);
}
}
}
}
解决方案
Based on your comments, I thing you are trying to reach the child in a wrong way.
Start by calling each gameObject with a name. For example:
MainGameObject
ChildCapsule
ChildText
Now, to access the child do like this:
public void SetHitObjectToActive(GameObject hitObject)
{
hitObject.transform.Find("ChildCapsule").gameObject.transform.Find("ChildText").gameObject.SetActive (true);
}