Unity 2D Ground colliders working, but not detected by OnTriggerEnter2D

Viewed 1030

I'm making my first Unity platformer and it occurred to me that I never stopped my player from jumping infinitely. I tried the typical solution of using a boolean value that is switched by jumping and colliding with the ground. The problem is even though my player does collide with the ground OnTriggerEnter2D doesn't seem to detect it.

And yes I have triple checked that the ground has the correct tag.

I tried using a raycaster solution but that didn't seem to work either. I have the code printing out the tag of any object it collides with so I know it's not detecting the ground at all.

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

public class PlayerController : MonoBehaviour
{

    //movement variables
    public float movex;
    public float speed;
    public float jumpforce;

    //interactivity variables
    public Rigidbody2D rb2d;

    private bool isJumping;

    Vector3 startingPosition;

    // Use this for initialization
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        startingPosition = transform.position;
    }

    // Update is called once per frame
    void Update()
    {        
        // localScale;
        if (Input.GetKeyDown(KeyCode.Space) && !isJumping)
        {
            rb2d.velocity = new Vector2(rb2d.velocity.x, jumpforce);
            isJumping = true;
        }

    }

    void OnTriggerEnter2D(Collider2D col) 
    {
        Debug.Log(col.tag);

        if (col.gameObject.CompareTag("Floor"))
        {
            isJumping = false
        }      
    }
}
2 Answers

So I realised it was because the collider on the ground wasn't set to be a trigger. I added a second box collider that it a trigger and it works as intended now.

Good job on finding the error on your own, OP. Your solution is usually the case :) You will probably have issues with collisions in the future. I've found that the main issues when people have problems with collisions not triggering are:

  1. You're using 3D collider components in a 2D game.
  2. None of the colliding objects have a Rigidbody(2D).
  3. The object the script is attached to doesn't have a Collider component
  4. The input parameter is Collision when it should be Collider or vice versa.
  5. The isTrigger boolean is not set (for OnTriggerEnter(2D))
  6. The script is not attached to the object
  7. You programatically exclude layers to collide. You can also set this in the project settings through a matrix. (Usually not the case since if you've done this you probably know what you're doing)
  8. Your object is moving too fast and you don't have Continous Collision Mode set (a dropdown on your Collider comonent)
Related