unity on gameobject active code example

Example 1: unity c# set gameobject active

gameObject.SetActive(true)

Example 2: how to disable a gameObject unity c#

public GameObject gameObj;//the gameobject you want to disable in the scene

        gameObj.SetActive(true); //set the object to active
        gameObj.SetActive(false);//set the object to disable

        gameObject.SetActive(true);//change the state of the current gameobject to active
        gameObject.SetActive(false);//change the state of the current gameobject to disable

Example 3: on GAMEOBJECT enable unity

void OnEnable()
    {
        Debug.Log("PrintOnEnable: script was enabled");
    }

Example 4: gameObject active

using 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;
        }
    }
}