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.