Enable and Disable Component in Unity – Unity By Example

Enable and Disable Component in Unity

How to enable and disable components via script

Steps

  • Create script EnableAndDisableComponent.cs
using UnityEngine;

[RequireComponent(typeof(BoxCollider))]
public class EnableDisableComponent : MonoBehaviour
{
	[SerializeField] private KeyCode _key = KeyCode.F;
    
    private BoxCollider _collider;

    private void Start()
    {
        _collider = GetComponent<BoxCollider>();
    }

    private void Update()
    {
        if (Input.GetKeyDown(_key))
        {
            _collider.enabled = !_collider.enabled;
        }
    }
}
  • Add script to game object.
  • Press Play and press key F to enable/disable box collider.

Result

Download

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments