Collision Detection and Colors

I am currently developing a game where i want the player to fall through objects depending on whether they the same color as that object. I have managed so far to disable the collider when the player is a different colour to the object. The problem arises however after the player has fallen through the object. The player continue to falls through the ground despite me enabling the collider once again.

 void OnCollisionEnter2D(Collision2D _Collision)
   {
    
   if(_Collision.rigidbody.renderer.material.color != this.renderer.material.color)
    	    {
    			_Collision.collider.enabled = false;
                }
    }
    void OnCollisionExit2D(Collision2D _Collision)
    {
        _Collision.collider.enabled = true;
    }

Thank you in advance

A couple things wrong here:

A) You’re disabling the block’s collider, not the players.

B) You’re checking everything that the player collides with to see if their color is not equal to the player’s. If it’s not, then you’re disabling that block’s collider.

I think you mean to be checking to see if the two colors are the same. In that case you should change your conditional to the following:

if(_Collision.renderer.material.color == renderer.material.color)

Also, you may wish to be disabling the player’s collider, in which case you’d do the following:

collider.enabled = false;

and not

_Collision.collider.enabled = false;

Finally, if you elect to toggle the player’s collider, and if the 2D stuff is anything like the 3D stuff, there is a parameterless version of OnCollisionExit that doesn’t require Unity to generate a bunch of collision data. Try replacing the following:

void OnCollisionExit2D(Collision _Collision)

with

void OnCollisionExit2D()

I know I’m very late but the problem could be the fact that once you disable the collider upon entering, the collider can no longer detect the OnCollosionExit because it’s disabled . A better way to do this would be to apply the disabling collider to the object you want it to pass through and not the player character itself.