How to Enable and Disable Components/GameObjects in C# for Unity
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…