user3583094
user3583094

Reputation: 105

How To Ignore Collision Between Two Objects On The Call Of A Script In Unity3D?

Basically, what I want to do is have two objects (fpscontroller and a wall) that collide like normal. But, once a script runs, they won't collide anymore. So, how do I make that script that makes the two objects ignore collision with each other? I've tried looking this up, and what I got was Physics.IgnoreCollision, but the documentation on that confused me. And when I tried putting it in and replacing their variables with my variables, I got a bunch of errors. So, please help.

Upvotes: 1

Views: 3092

Answers (1)

Eissa
Eissa

Reputation: 700

The way i would go about doing this is through layers.

In unity, a convenient way to ignore physics collision between objects is through setting the object to be ignored to a layer which your player object will always ignore.

So, to go about setting this up imagine the following:

fpscontroller's layer is set to "player" (a layer i have created and named such).

wall's layer is initially always set to "wall" (once again a layer i have created)

Additionally, I create a layer that i call "IgnorePlayerCollisions"

Now i go to: Edit > Project Settings > Physics Here i can check the box which will turn off collisions between my player and IgnorePlayerCollisions layers.

Now, at runtime i run my script which says:

Change Wall Layer to "IgnorePlayerCollisions". Voila, my player now ignores all collisions with this layer.

Code Examples: (You don't need these all):

// Function to Change a GameObject Layer to the Ignore Layer
public void ChangeGameObjectLayerToIgnore(GameObject go) {
    go.layer = [Index of Ignore Layer];
}

// Function to Change "This" GameObjects layer to any other layer
public void ChangeThisGameObjectLayer(int layerIndex) {
    this.gameObject.layer = layerIndex;
}

// Change a GameObject layer to another layer
public void ChangeGameObjectLayer(GameObject go, int layerIndex) {
    go.layer = layerIndex;
}

How?

Place a C# function into a script and attach it to either your desired gameobject. In your case, i may attach it my Player GameObject since it seems like you may want to disable object throughout the game based on specific trigger or something. It really depends on how you plan to trigger the function.

Let me know if this makes sense or not. If not, i can attempt to make it more legible.

Good luck and have fun!

Upvotes: 1

Related Questions