Hi, i have this simple on and off script, switching off works well but switching on doesn't, the object's mesh doesn't appear again

public class click : MonoBehaviour
{

private Renderer ren;
private Collider CO;

void Update()
{
    
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if (Physics.Raycast(ray, out hit))
    {
        if (hit.collider != null)
        {
            
                    if (Input.GetMouseButtonDown(0))
                    
                         //hit.collider.enabled = false;
                        {
                            hit.collider.GetComponent<Renderer>().enabled = false;
                        }

                    if (Input.GetMouseButtonDown(0))
                       {
                            hit.collider.GetComponent<Renderer>().enabled = true; 
                      }//hit.collider.enabled = false;
                    
        }               
        

    }

2 Answers

2

Try this:

public class click : MonoBehaviour
{
    private Camera camera ;
    void Start()
    {
        camera = Camera.main ;
        if( camera == null )
            camera = FindObjectOfType<Camera>();
    }
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = camera.ScreenPointToRay(Input.mousePosition);
            if( Physics.Raycast(ray, out hit) && hit.collider != null )
            {
                Renderer renderer = hit.collider.GetComponent<Renderer>();
                renderer.enabled = !renderer.enabled;
            }
        }
    }
}

nice, works well ,thanks

–

nice, works well ,thanks