# Unhiding/Hiding Objects During Gameplay

## Using SetActive()

Use the script below to make a game object visible and its components available:&#x20;

```csharp
this.gameObject.SetActive(true);
```

And unavailable:

```csharp
this.gameObject.SetActive(false);
```

Swap "this" with the variable name for a gameObject type.

**Note:** "gameObject" is only needed if the variable used is of a different type.&#x20;

{% hint style="warning" %}
Scripts cannot access components of objects that are not active.
{% endhint %}

## Example Code

Examples of a game object called "thing" that appears when "F" is pressed and disappears when "X" is pressed:

### **Example 1** (using a gameObject type):

```csharp
using UnityEngine;

public class AppearDisappear : MonoBehaviour
{
    public GameObject thing;
    
    void Update
    {
        if (Input.GetKeyDown(KeyCode.F) {
            thing.SetActive(true);
        }
        
        if (Input.GetKeyDown(KeyCode.X) {
            thing.SetActive(false);
        }
    }
}
```

### **Example 2** (using a variable of another type):

```csharp
using UnityEngine;

public class AppearDisappear : MonoBehaviour
{
    public Transform thing;
    
    void Update
    {
        if (Input.GetKeyDown(KeyCode.F) {
            thing.gameObject.SetActive(true);
        }
        
        if (Input.GetKeyDown(KeyCode.X) {
            thing.gameObject.SetActive(false);
        }
    }
}
```

{% hint style="danger" %}
**REMEMBER:** Hiding a parent object will hide its children.
{% endhint %}

## **Checking If the Game Object is Active**

This code can help if you want things to behave differently if an object is visible or not.

```csharp
this.gameObject.activeSelf
```

It is read-only (you cannot directly change this value) and will return true if active and false if not.

In the Hierarchy window, hidden / inactive objects will appear grayed out:

![](https://3795241431-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M8XSUYVSlHMdPUNud-2%2F-M9HmF8ZoJ-P8G8jGz1Y%2F-M9KQThPRzYbTQ6hEx9D%2Fimage.png?alt=media\&token=da336788-276c-45e4-9d7f-49a7948a7142)

In the Inspector window, the checkbox next to the object's name controls the active state of the object. Example of an inactive object:

![](https://3795241431-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M8XSUYVSlHMdPUNud-2%2F-M9HmF8ZoJ-P8G8jGz1Y%2F-M9KQoarlVefOT-mceEi%2Fimage.png?alt=media\&token=b00d9f85-a3c7-421b-b271-66e7fce18012)

{% hint style="warning" %}
REMEMBER: Add the script to a game object in the scene. It will not work if it does not exist in the game.
{% endhint %}

{% content-ref url="../../select/update-game-objects" %}
[update-game-objects](../../select/update-game-objects)
{% endcontent-ref %}

{% content-ref url="../../delete/delete-game-objects" %}
[delete-game-objects](../../delete/delete-game-objects)
{% endcontent-ref %}

