r/UnityHelp • • Aug 03 '21

Question: How Do You Disable Specific Collisions

I am attempting to create a sort of dodge ability for the player in my 2D platformer. But, I do not know how you are supposed to disable/enable certain collisions. Is it possible to put colliders on layers so that they only collide with other colliders on that layer, or something to that effect? Or do you have to manually enable and disable specific collisions?

3 Upvotes

5 comments sorted by

1

u/Bonejob Code Guru Aug 03 '21

The collisions are just the event that starts a process. When that event occurs you can determine if the collision was "dodged" and if so fire a different sequence of events. So collisions always happen it's what you do with it after the collision that is the solution.

1

u/[deleted] Aug 04 '21

After you replied, I went into the unity manual and read through the scripting on events and collision events. What I am not sure about is: A, Exactly how to access the collision event. B, What sort of command I need to use in order to prevent the physical collision while keeping my collider.

I'm pretty new to C# and Unity in general, so it's taking me a little while to figure out how the code interacts with the unity editor.

I'll include a screenshot of the code I have written that isn't working.

1

u/Bonejob Code Guru Aug 04 '21

You could do something like this

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class collide : MonoBehaviour
{

    private void Start()
    {
        Debug.Log("Start collider check");
    }
    void OnCollisionEnter(Collision collision)
    {
        //Output the Collider's GameObject's name
        Debug.Log(collision.collider.name);
    }

    //If your GameObject keeps colliding with another GameObject with a Collider, do something
    void OnCollisionStay(Collision collision)
    {
        //Check to see if the Collider's name is "Chest"
        if (collision.collider.name == "Player")
        {
            //Output the message
            Debug.Log("Player Colided");
            //Player dodged if greather than 5
            if(Random.Range(1,10) >= 5)
            {
                collision.collider.enabled = false;
            }
        }
    }
}

This is off the top of my head and has not been tested.

Here is another method using OnTriggerEnter2d

https://samarthdhroov.medium.com/making-the-enemy-dodge-players-attack-in-unity-8f9204da5f57

1

u/[deleted] Aug 05 '21

Thanks you, I hope this works!

1

u/Bonejob Code Guru Aug 05 '21

If not we will figure somthing out :)