- Home /
How to SetActive an object with a raycast?
Hi everyone,
For a project I create a raycast attached to my camera, and beside I have a GameObject with obviously a collider, and i would like when the raycast triggers the GameObject's collider, the GameObject appears. The idea was to show game object only when they are in front of the camera, other wise they are invisible.
But i failed.
I certainly messed up somewhere in my code, so can the community help me?
here the code of the raycast: void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit hit;
float TheDistace;
Vector3 forward = transform.TransformDirection (Vector3.forward) * 10;
Debug.DrawRay (transform.position, forward, Color.green);
if (Physics.Raycast (transform.position, (forward), out hit)) {
TheDistace = hit.distance;
print (TheDistace + " " + hit.collider.gameObject.name);
}
}
}
And here the code for the game object: public GameObject Image;
void Start() {
Image.SetActive (false);
}
void OnTriggerEnter (Collider player) {
if (player.gameObject.tag == "Player") {
Image.SetActive (true);
}
}
}
Thanks for your help! :)
Answer by MT369MT · Jun 16, 2018 at 09:13 PM
Hi, I think that you cant use OnTriggerEnter to detect a Raycast. I tried to edit your code so:
private void Update()
{
RaycastHit hit;
float TheDistace;
Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
Debug.DrawRay(transform.position, forward, Color.green);
if (Physics.Raycast(transform.position, (forward), out hit))
{
TheDistace = hit.distance;
print(TheDistace + " " + hit.collider.gameObject.name);
if (hit.collider.tag == "Object")
{
hit.collider.gameObject.GetComponent<MeshRenderer>().enabled = true;
}
}
}
When the Raycast detect a gameobject it will check the tag of that object and if true it will enable the MeshRenderer of that GameObject (if you disable the whole object it cant detect the raycast because also the collider will be disabled).