- You can go to Edit->Project Setting->Physics or Physics 2D->Layer Collision Matrix. To change what you want your player pass through or not.
- To change it via code like what you wanted, I have a solution here. Ex: your Player's Layer position is 6 & your Enemy is 7.
private bool isSwimmingUnderWater = false;
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
isSwimmingUnderWater = !isSwimmingUnderWater;
Physics2D.IgnoreLayerCollision(6, 7, flagisSwimmingUnderWater); //it will set the val of the Layer Collision of the Player and Enemy whether true or false
}
}
I have tested it with my game and it works.
