Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get access to "mesh renderer" of a different object using raycast?

For example, a camera that generates Raycast and if it hits it destorys an object.

public class RaycastScript : MonoBehaviour
{
    void CheckForRaycastHit()
    {
        RaycastHit hit;

        //if raycast hit 
        if(Physics.Raycast(transform.position, transform.forward, out hit))
        {
            print(hit.collider.gameObject.name + " hit");       //print what object got hit
            Destroy(hit.collider.gameObject);                   //destroy object
        }
    }
    void Update()
    {
        //mouse controls camera
        float mouseX = Input.GetAxis("Mouse X");
        float mouseY = Input.GetAxis("Mouse Y");

        transform.Rotate(-mouseY, 0, 0);
        transform.Rotate(0, mouseX, 0,Space.World);

        CheckForRaycastHit();
    }
}

Instead of destroying I want to disable mesh renderer so the object is invisible but still there.
I have been trying playing around with ".GetComponent()", looking in Unity documentation and some other things but I could not figure it out.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Get Mesh Renderer like bellow:

var meshRenderer = hit.collider.GetComponent<MeshRenderer>();

if (meshRenderer) meshRenderer.enabled = false;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading