Home > Net >  OnTriggerEnter2D is not detecting gameObject tag
OnTriggerEnter2D is not detecting gameObject tag

Time:05-30

I'm writing a simple line of code that is when the player jump into the spike, it will trigger the death animation. I try OnTriggerEnter2D but it not working, maybe because of sorting layer? I also try to change the spike layer to be the same as the player layer but it still not working.

here the code:

using UnityEngine;
using System.Collections;

public class HeroKnight : MonoBehaviour {

[SerializeField] float      m_speed = 4.0f;
[SerializeField] float      m_jumpForce = 7.5f;
[SerializeField] float      m_rollForce = 6.0f;
[SerializeField] bool       m_noBlood = false;
[SerializeField] GameObject m_slideDust;

private Animator            m_animator;
private Rigidbody2D         m_body2d;
private Sensor_HeroKnight   m_groundSensor;
private Sensor_HeroKnight   m_wallSensorR1;
private Sensor_HeroKnight   m_wallSensorR2;
private Sensor_HeroKnight   m_wallSensorL1;
private Sensor_HeroKnight   m_wallSensorL2;
private bool                m_isWallSliding = false;
private bool                m_grounded = false;
private bool                m_rolling = false;
private int                 m_facingDirection = 1;
private int                 m_currentAttack = 0;
private float               m_timeSinceAttack = 0.0f;
private float               m_delayToIdle = 0.0f;
private float               m_rollDuration = 8.0f / 14.0f;
private float               m_rollCurrentTime;


// Use this for initialization
void Start ()
{
    m_animator = GetComponent<Animator>();
    m_body2d = GetComponent<Rigidbody2D>();
    m_groundSensor = transform.Find("GroundSensor").GetComponent<Sensor_HeroKnight>();
    m_wallSensorR1 = transform.Find("WallSensor_R1").GetComponent<Sensor_HeroKnight>();
    m_wallSensorR2 = transform.Find("WallSensor_R2").GetComponent<Sensor_HeroKnight>();
    m_wallSensorL1 = transform.Find("WallSensor_L1").GetComponent<Sensor_HeroKnight>();
    m_wallSensorL2 = transform.Find("WallSensor_L2").GetComponent<Sensor_HeroKnight>();
}

//Here the Trigger event
void OnTriggerEnter2D(Collider2D col)
{
    if (gameObject.tag == "Spike")
    {
       Debug.Log("OnTriggerSEnter2D");
        //Death
        m_animator.SetBool("noBlood", m_noBlood);
        m_animator.SetTrigger("Death");
    }
}

CodePudding user response:

You're not looking for the collider tag, your looking HeroKnight's gameobject instead.

CodePudding user response:

In fact, gameObject.tag checks the player tag itself. You must write the code as follows. Also consider that the CompareTag command is more efficient.

public void Update()
{
    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.CompareTag("Spike"))
        {
            Debug.Log("OnTriggerSEnter2D");
            //Death
            m_animator.SetBool("noBlood", m_noBlood);
            m_animator.SetTrigger("Death");
        }
    }
}
  • Related