I'm right now using Unity for a school project and I need to be able to hide and unhide sprites for "expansions".

I've looked all over the internet for this and I can't seem to find an answer.

Here is the script so far:

using System.Collections;
using Systems.Collections.Generic;
using UnityEngine;

public class addBlock : MonoBehaviour{

  void OnMouseDown()
  • \$\begingroup\$ Is this a UI Element or an in game element? Must you click on the element itself or are you just looking for anytime you press the mouse down? OnMouseDown isn't a default monobehaviour function. You need an event system to make it work, and the event system will only work with UI elements (Image) that can receive special UI raycasts. \$\endgroup\$ – gjh33 May 3 '19 at 14:51

"I looked all over the internet" and somehow completely missed the enabled checkbox? ;)

public class HideShowOnClick : MonoBehaviour {

    Renderer visual;

    void Start() {
        visual = GetComponent<Renderer>();

    void OnMouseDown() {
        // If it was shown, hide it. If it was hidden, show it.
        visual.enabled = !visual.enabled;

Make sure your object has both a renderer attached (can be a SpriteRenderer, MeshRenderer, etc), and an appropriately-shaped/sized collider to detect whether the mouse click hits it. Because we turn off only the visual, the collider is still there to capture the click to trigger it to turn back on.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.