SetActive(bool)
Activates or deactivates the GameObject locally, according to the value of the supplied parameter.
Read time 1 minuteLast updated 5 days ago
Definition
- Type: Method
- Namespace: UnityEngine
- Assembly: UnityEngine.CoreModule
public void SetActive(bool value)
Parameters
The active state to set, where sets the GameObject to active and sets it to inactive.
truefalseRemarks
SetActiveactiveInHierarchyfalseDeactivating a GameObject disables each component, including attached renderers, colliders, rigidbodies, and scripts. For example, Unity will no longer call MonoBehaviour.Update() on a script attached to a deactivated GameObject. Deactivating a GameObject also stops all coroutines attached to it.
Note: If the call to changes the value of GameObject.activeInHierarchy, this triggers MonoBehaviour.OnEnable() or MonoBehaviour.OnDisable() on all attached MonoBehaviour scripts.
SetActiveusing UnityEngine;public class Example : MonoBehaviour{ private GameObject[] cubes = new GameObject[10]; public float timer, interval = 2f; void Start() { Vector3 pos = new Vector3(-5, 0, 0); for (int i = 0; i < 10; i++) { cubes[i] = GameObject.CreatePrimitive(PrimitiveType.Cube); cubes[i].transform.position = pos; cubes[i].name = "Cube_" + i; pos.x++; } } void Update() { timer += Time.deltaTime; if (timer >= interval) { for (int i = 0; i < 10; i++) { int randomValue = Random.Range(0, 2); if (randomValue == 0) { cubes[i].SetActive(false); } else cubes[i].SetActive(true); } timer = 0; } }}
Additional Resources: GameObject.activeSelf, GameObject.SetGameObjectsActive