public void SetActive (bool value);

Parameters

valueActivate or deactivate the object, where true activates the GameObject and false deactivates the GameObject.

Description

Activates/Deactivates the GameObject, depending on the given true or false value.

A GameObject may be inactive because a parent is not active. In that case, calling SetActive will not activate it, but only set the local state of the GameObject, which you can check using GameObject.activeSelf. Unity can then use this state when all parents become active.

Deactivating a GameObject disables each component, including attached renderers, colliders, rigidbodies, and scripts. For example, Unity will no longer call the Update() method of a script attached to a deactivated GameObject. OnEnable or OnDisable are called as the GameObject received SetActive(true) or SetActive(false).

using UnityEngine;

// GameObject.SetActive demo. // // Show a column of cubes. Any cube can be clicked by the mouse // and have SetActive set to false. The cubes beneath the hidden // cube will not have SetActive set to false, but will not be // shown. This is the feature of SetActive. Also, the cubes have // SetActive set back to true 2 seconds after they are hidden.

public class Example : MonoBehaviour { private GameObject[] gameObjects; private int numberOfGameObjects = 5; private float delay = 2.0f;

void Awake() { // Create some GameObjects. gameObjects = new GameObject[numberOfGameObjects];

for (int i = 0; i < numberOfGameObjects; i++) { // Create, place in the world, and set name. gameObjects[i] = GameObject.CreatePrimitive(PrimitiveType.Cube); gameObjects[i].transform.position = new Vector3(0.0f, -1.5f * i, 0.0f); gameObjects[i].name = i.ToString();

// The first GameObject is the top parent, so ignore it for now. if (i > 0) { gameObjects[i].transform.parent = gameObjects[i - 1].transform; } } }

private float startTime = 0.0f; private bool increaseTime = false;

void Update() { if (Input.GetMouseButtonDown(0)) { RaycastHit hitInfo = new RaycastHit(); bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);

// Set GameObject SetActive to false when // hit by a mouse click. if (hit) { hitInfo.transform.gameObject.SetActive(false);

startTime = 0.0f; increaseTime = true; } }

// Show the GameObjects when time exceeds delay. if (increaseTime) { startTime += Time.deltaTime; if (startTime > delay) { for (int i = 0; i < numberOfGameObjects; i++) { // Note that some of the GameObjects // might have true already. gameObjects[i].SetActive(true); }

increaseTime = false; } } }

// Show time. void OnGUI() { GUIStyle fontSize = new GUIStyle(GUI.skin.GetStyle("label")); fontSize.fontSize = 24; GUI.Label(new Rect(10, 10, 250, 50), "Time: " + startTime.ToString("F2"), fontSize); } }