Hi there, welcome back to another Game development tip, talking about Unity this time!
In this post, I'm gonna show you how to enable and disable a Box Collider component from a Game Object using a single line of C# code.
First of all, make sure you've added the Box Collider component to your Game Object, you can do so by clicking the [Add Component] button from the Inspector panel in Unity and searching for Box Collider from the dropdown list, then select it
Make sure you've declared the Game Object you've attached the Box Collider to in your C# script
public class GameScene: MonoBehaviour {
// Declare your Game Object and attach it in the Editor!
public GameObject MyGameObject;
Then, just for the sake of this tutorial, let's call 2 functions that detect the Mouse button click down and up. I'll insert the lines of code to enable and disable the Box Collider inside those functions, so you'll be able to run your game in the editor and test it right away
void Update(){
if (Input.GetMouseButtonDown(0)) {
// Disable BoxCollider on click
MyGameObject.GetComponent<BoxCollider>().enabled = false;
}
if (Input.GetMouseButtonUp (0)) {
// Disable BoxCollider by lifting the finger from the mouse button
MyGameObject.GetComponent<BoxCollider>().enabled = true;
}
If you've done it correctly, this should be the result you'll get:
That's all for this tutorial, I hope you enjoyed it!
Stay tuned for new posts, and Follow me on Twitter @xsgames_ or Subscribe to my YouTube channel
And if you like my work, feel free to buy me a Beer 🍺 (yeah, I can't drink coffee, unfortunately :)
Your support will be greatly appreciated ❤️🔥
See you next time! 👋