Activating and deactivating gameObjects in unity by C# script

Sometimes it is very useful to active or deactivate a gameObject by script. For this gameObject class have a called SetActive(). You can pass true or false in to active or deactivate

  • For activating gameObject by script first declare a gameObject and then drag and drop in inspector or use Find method for referencing gameObject.
  • then use gameObject.SetActive(true) when you want to visible (activate) gameObject.SetActive(false) when want to deactivate gameObject.
  • if gameObject is parent object then its all child object will also deactivaate.

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

public class test : MonoBehaviour
{
    public GameObject my_object;
    // Start is called before the first frame update
    void Start()
    {
      
    }

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.A))
        {
            my_object.SetActive(true);//activate gameObject
        }

        if(Input.GetKeyDown(KeyCode.D))
        {
            my_object.SetActive(false);//deactivate gameObject
        }
    }
}

  • In this example code we have declare a gameObject of name my_object.
  • if we press 'A' key then my_object.SetActive(true); code will execute an active gameObject.
  • and if press 'D' key then my_object.SetActive(true); will deactivate gameObject.
  • You can use these code to your desired gameObject at desire place of code

You can also use array of gameObject for multiple gameObjects to active or deactivate

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

public class test : MonoBehaviour
{
    public GameObject[] my_object;
    // Start is called before the first frame update
    void Start()
    {
      
    }

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.A))
        {
            for(int i=0;i<my_object.Length;i++)
            {
                my_object[i].SetActive(true);//activate gameObject
            }
        }

        if(Input.GetKeyDown(KeyCode.D))
        {
            for(int i=0;i<my_object.Length;i++)
            {
                my_object[i].SetActive(false);//deactivate gameObject
            }    
        }
    }
}


  • You can declare array of gameObjects and then can activate or deactivate particular or all gameObject with few line of code. 


Popular posts from this blog

How to fix Android Gradle Build failed error in unity

Changing position of gameObjects in unity by C# script

Finding a GameObject by C# script in unity

How to install unity editor

how to pause game by script in unity ( with android back button or with computer esc key )

WaitForSeconds and coroutine in unity | delaying a code action for some time in C#

Unity ads install error from package manager

Unity's interface - basic introduction to unity editor

Grid snapping in unity editor

Creating new project in unity hub