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.
CodePudding user response:
Get Mesh Renderer like bellow:
var meshRenderer = hit.collider.GetComponent<MeshRenderer>();
if (meshRenderer) meshRenderer.enabled = false;