- Home /
OnTriggerEnter2D is triggering when objects do not collide
So I have a player that needs to pass through the enemy and still have a life taken away. I cannot use OnCollision because then the physics of the enemy is transferred to the player. While I am playing lives are being taken away even though my player does not collide with my enemy. I have the enemy tagged to take a life away and i checked that no other objects contain this tag. Any help is appreciated. Attached is my GameOver script which really just takes a life.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameOver : MonoBehaviour
{
// Start is called before the first frame update
public Rigidbody2D rb;
public LifeManager lifeSystem;
public GameObject GameOverScreen;
public float waitAfterGameOver;
void Start()
{
rb = GetComponent<Rigidbody2D>();
lifeSystem = FindObjectOfType<LifeManager>();
}
public void OnTriggerEnter2D(Collider2D trigger)
{
if (trigger.gameObject.tag == "Ghost")
{
lifeSystem.TakeLife();
}
if (GameOverScreen.activeSelf)
{ waitAfterGameOver -= Time.deltaTime; }
}
Answer by I_Am_Err00r · Jul 11, 2019 at 02:12 PM
It doesn't look like there is any OnTriggerExit2D event, so basically when you are outside of the ghost you stop taking life.
public void OnTriggerExit2D(Collider2D trigger)
{
if (trigger.gameObject.tag == "Ghost")
{
StopTakingDamage();
}
}
Depending on how you have your damage system setup, something like this would work; you might just need to have a bool that defines if you should or shouldn't be taking damage.
Right after posting this I realized you could change the OnTriggerEnter to OnTriggerStay, and that would eliminate the need for the extra exit lines of code for the exit event.
thanks, I ended up destroying the ghost on contact to deal with my player being effected by physics. I will revisit this though
So, this is your GameOver script, but it's using OnTriggerEnter... So does this mean this GameObject has a large collider on it?
Shouldn't the player object be detecting the OnTrigger and not the GameOver script?