Changing properties of object hit with raycast

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;
        }
    }

Hello, you could store the object.

GameObject tempObject;

// then in the raycast

tempObject = hit.collider.gameobject;

My guess is that a few frames pass between the time the mouse is down, and up again.

1 Like

If collider is disabled your Raycasting won’t work…

One solution would be to cast a ray on mouse down, and then store the object hit by the ray, before disabling the collider. then on mouse button up, you still have the cached object and you can do your final changes.

1 Like