OnTriggerEnter2D called without collision
I am kinda new to unity so please bear with me. I am making a 2D game where the player and the enemy game object both have colliders. There are different types of enemies which generally have either box collider 2d or polygon colliders 2d. When the game starts i spawn the player and spawn obstacles every 2.5 seconds using a coroutine. To each enemy, i have a trigger collider and a script attached to check if it has collided with the player. The problem is that the OnTriggerEnter2D method is called sometimes at the very start of the game when the first enemy is spawned and the enemy has not even touched the player. Hence my player dies at the beginning of the game. This is random as in, it happens with different enemies.. and it happens once in 10 times when i play the game in editor. I am stuck on this problem for 3 days.. please help
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.CompareTag ("Player")) {
if (other.gameObject.GetComponent<PlayerController> ().isDead == false) {
if (gameObject.CompareTag ("Destroyable") && !playerController.ispassThroughSpellCasted ()) {
Destroy (gameObject);
print ("setting player dead 3");
playerController.playerIsDeadOrNo (true);
} else if (gameObject.CompareTag ("FallsToGround")) {
if (!playerController.ispassThroughSpellCasted ()) {
print ("setting player dead 2 with gameobject : " + gameObject.name);
playerController.isDead = true;
} else {
switch (PlayerPrefs.GetInt ("levelNo")) {
case 0:
TriggerKidLevel ();
break;
case 1:
TriggerNormalLevel ();
break;
case 2:
TriggerProLevel ();
break;
}
playerController.isDead = false;
}
} else {
if (!other.gameObject.GetComponent<PlayerController> ().ispassThroughSpellCasted ()) {
playerController.isDead = true;
print ("setting player dead 1 with gameobject : " + gameObject.name);
if (gameObject.GetComponent<Animator> () != null) {
gameObject.GetComponent<Animator> ().SetTrigger ("playerIsDead");
}
return;
} else {
playerController.isDead = false;
}
}
}
}
}
The line "setting player dead 1 with gameobject : " is printed on logs with different enemy object names each times...
Verify that is not a enemy with tag 'Player'.
Add this lines before 'playerController.isDead = true'
Debug.Log("Hi", this); Debug.Break();
This is going to mark the enemy how is killing the player, in the hierarchy tab and pause the game and maybe you can see what is happening.
Your answer
Follow this Question
Related Questions
2D Collision Best Practice 0 Answers
how to load panels in a platformer game? 0 Answers
How to make fast a coroutine 1 Answer
How to stick to an object when a button is pressed Unity 2d 0 Answers
Unity 2d Collision Glitch Help 0 Answers