How to check collision between the player and a specific TileBase object in Unity?

Viewed 1612

I have a couple of tilebase variables that are set using the unity inspector:

public TileBase obstacle; //obstacle tile
public TileBase spikes; //instant death tile

I'm using OnCollisionEnter2D in a script that is set to the tilemap asset.

void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.name == "Player")
    {
        PlayerPrefs.SetInt("Collision", 1);
    }
}

I want to be able to detect when the player has collided with the spikes TileBase as that should trigger a game over. The asset name that is set to the spikes variable through the inspector is also called Spikes or Spikes (Tile) in the palette.

I tried using adding collision detection to a script that is used on the player asset to check what objects it collides with

void OnCollisionEnter2D(Collision2D col)
{
    Debug.Log(col.gameObject.name);
}

But all it comes back with is the name of the tilemap.

1 Answers

First you should add Layers to your objects. An easy example is to add a "TileBase" or "Tile" Layer to your TileBase objects.

You can then allow your Player to only collide with certain things and NOT your tilemap. See the collision matrix for this.

Then alter your code like this:

void OnCollisionEnter2D(Collision2D col)
{
    var tilebase = col.GetComponent<TileBase>();
    if (tilebase != null)
    {
        Debug.Log(tilebase.gameObject.name);
    }
}
                          
Related