Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

OnTriggerEnter not working

Discussion in 'Scripting' started by Kinkku2, May 19, 2015.

  1. Kinkku2

    Kinkku2

    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. OneDragutin

    OneDragutin

    Joined:
    May 10, 2015
    Posts:
    326
    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. Kinkku2

    Kinkku2

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