Remove Collider from a GameObject in Unity3D C#
In this game development tutorial, you will learn how to remove the Collider component from a game object with the help of C# programming.
You often may need to destroy the collider of an object during GamePlay. For example, after an event, you may want to remove the collider from the player.
In order to remove the collider from an object, you first have to get the collider component that is attached to that GameObject. After that, you have to use the Destroy()
function and pass the collider component variable as the parameter to the function. Below is given the simple C# code for this:
void Start() { Collider colliderComponent = GetComponent<Collider>(); Destroy(colliderComponent); }
Now look at the above code. The piece of code inside the Start()
method will remove the collider from our game object.
In the above code example, we are not checking if the collider component is attached to the GameObject or not. It may create issues during the gameplay. So we have to do something to overcome this.
Well, we already have the solution for this. It is always better to check if the collider is attached and if it is already there, then remove the collider component. We can do this task by simply using an if...else
statement as you can see in the example below:
void Start() { Collider colliderComponent = GetComponent<Collider>(); if (colliderComponent != null) { Destroy(colliderComponent); } else { Debug.Log("GameObject doesn't have Collider component."); } }
As you can see, we use if...else
statement to check if colliderComponent
value is not null
. In the else block, we simply show a message in the console that the Collider component is not found on the GameObject.
Leave a Reply