Im working on having an object change color and its collision box be disabled when the player clicks on it, it works, my issue is that it wont change back as soon as the player stops pressing it.
It comes back with a null reference on this line :
hit.collider.gameObject.GetComponent<MeshRenderer>().material.color = new Color32(255, 0, 0, 255);
.
I understand that hit is no longer assigned a value but why? And how do i fix it
public void RayCasting()
{
RaycastHit hit = new RaycastHit();
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(ray.origin, ray.direction * 30, Color.green);
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(ray, out hit, 30))
{
if (hit.collider.tag == "Switch")//Deactivate the switch
{
hit.collider.gameObject.GetComponent<MeshRenderer>().material.color = new Color32(0, 255, 0, 255);
hit.collider.gameObject.GetComponent<Collider>().enabled = false;
}
if (hit.collider.tag == "Button")//deactivate the button
{
hit.collider.gameObject.GetComponent<MeshRenderer>().material.color = new Color32(0, 255, 0, 255);
hit.collider.gameObject.GetComponent<Collider>().enabled = false;
}
}
}
if (Input.GetMouseButtonUp(0))
{
hit.collider.gameObject.GetComponent<MeshRenderer>().material.color = new Color32(255, 0, 0, 255);
hit.collider.gameObject.GetComponent<Collider>().enabled = true;
}
}