Search Unity

OnTriggerEnter not working

Discussion in 'Scripting' started by matias-e, May 19, 2015.

  1. matias-e

    matias-e

    Joined:
    Sep 29, 2014
    Posts:
    106
    So I have this bit of code which is similar to the one given in the 'Roll-a-Ball' tutorial:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Player : MonoBehaviour {
    5.  
    6.     public float speed = 2.0f;
    7.     private Rigidbody2D rb;
    8.  
    9.     // Use this for initialization
    10.     void Start () {
    11.  
    12.         rb = GetComponent<Rigidbody2D>();
    13.    
    14.     }
    15.    
    16.     // Update is called once per frame
    17.     void Update () {
    18.  
    19.         float moveHorizontal = Input.GetAxis("Horizontal");
    20.         Vector2 movement = new Vector2(moveHorizontal, 0.0f);
    21.  
    22.         rb.AddForce(movement * speed);
    23.    
    24.     }
    25.  
    26.     void OnTriggerEnter (Collider other) {
    27.         if(other.gameObject.CompareTag("Collectible")) {
    28.             BallCreate.score++;
    29.             Debug.Log("went");
    30.             Destroy(other.gameObject);
    31.         }
    32.     }
    33. }
    For some reason the collectible does not notice the trigger enter. The collectible has the 'Collectible' tag with a big C and all of my stuff has 2D colliders on them + the player ball has a 2D rigidbody. I had the other.tag == "Collectible" in the if clause at first, but it didn't work with that either. When I turn off the 'is trigger' checkbox on the collectible, my player ball is stopped by its collider. Really weird. What could be wrong?
     
  2. Nitugard

    Nitugard

    Joined:
    May 10, 2015
    Posts:
    343
    You can't use OnTriggerEnter with 2D colliders cause it only works with 3D.
    There is a separate function that works with 2D colliders, which is:
    Code (CSharp):
    1. void OnTriggerEnter2D (Collider2D other)
    Hope this solve your issue!
     
  3. matias-e

    matias-e

    Joined:
    Sep 29, 2014
    Posts:
    106
    Ooh, that worked! Thanks man. Haven't dabbled in 2D a lot yet, so that was new.