Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

OnTriggerEnter2D not working

Discussion in 'Scripting' started by markenzo51, May 22, 2020.

  1. markenzo51

    markenzo51

    Joined:
    Sep 15, 2018
    Posts:
    3
    This is a script for moving platforms in a platformer game, the platform are supposed to turn around when hitting a trigger collider, but for some reason it doesn't work. The trigger is an empty with a box collider 2D, when I tried to make it a normal collider and interact with the player, it didn't work either, so maybe that is the problem, but I have no idea on what's exactly wrong with that

    Code (CSharp):
    1. using System.Collections;
    2.     using System.Collections.Generic;
    3.     using UnityEngine;
    4.    
    5.     public class MovingObject : MonoBehaviour {
    6.    
    7.         [SerializeField]public Vector2 velocity;
    8.         int direction=1;
    9.  
    10.         void Update ()
    11.         {
    12.             transform.Translate(direction * velocity * Time.deltaTime);
    13.         }
    14.  
    15.         void OnTriggerEnter2D(Collider2D trigger){
    16.             if(trigger.gameObject.layer==12){
    17.                 direction=-direction;
    18.             }
    19.         }
    20.  
    21.     }
    22.  
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Add a log statement to make sure the method is actually getting called in the first place:
    Code (CSharp):
    1.         void OnTriggerEnter2D(Collider2D trigger){
    2.             Debug.Log("OnTriggerEnter2D called");
    3.             if(trigger.gameObject.layer==12){
    4.                 direction=-direction;
    5.             }
    6.         }
     
    Kurt-Dekker likes this.
  3. markenzo51

    markenzo51

    Joined:
    Sep 15, 2018
    Posts:
    3
    I already tried that. The method isn't called at all. I also tried to make the box collider bigger to check if maybe that was the problem, but still didn't work.
     
  4. leftshoe18

    leftshoe18

    Joined:
    Jul 29, 2017
    Posts:
    61
    Is there a Rigidbody2D on the collider or the platform? I haven't done any 2D stuff in Unity but I know you need Rigidbodies to make colliders work in 3D.
     
    markenzo51 likes this.
  5. markenzo51

    markenzo51

    Joined:
    Sep 15, 2018
    Posts:
    3
    Yeah that was the issue. I thought that the rigidbody wasn't needed for trigger collisions, but it looks like you do. Thanks
     
    leftshoe18 likes this.