How to Enable and Disable Components/GameObjects in C# for Unity

Karuna Ketan
2 min readDec 11, 2022

I learned how to Enable and Disable Components/GameObjects in Unity…

9th Programs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TextScript01 : MonoBehaviour
{
BoxCollider2D _col;

// Start is called before the first frame update
void Start()
{
_col = gameObject.GetComponent<BoxCollider2D>();
}

// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("space"))
{
_col.enabled = false; // _col.enabled = !_col.enabled;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TextScript02 : MonoBehaviour
{
[SerializeField] GameObject _squareParent;
[SerializeField] GameObject _square;

// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("space"))
{
// Debug.Log(_squareParent.activeSelf);
_squareParent.SetActive(false);
Debug.Log(_square.activeInHierarchy);
}
}
}

From above program:

if (Input.GetKeyDown("space"))
{
// Debug.Log(_squareParent.activeSelf);
_squareParent.SetActive(false);
Debug.Log(_square.activeInHierarchy);
}
  • If you press space bar then this program will disable the block or object on which this is applied on…and while pressing space again, it will get enabled…

That’s all…Thank you for Reading😅…

click here to follow me in LinkedIn for more updates…

click here to follow me in GitHub for more updates…

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Karuna Ketan
Karuna Ketan

Written by Karuna Ketan

Game Designer and Developer | Unity, Unreal Engine, Blender

No responses yet

Write a response