Hello,
My code has been working fine, but my project got sidetracked for about a year.
I’m now working with the latest Unity version and I noticed my OnTriggerEnter2D is being executed multiple times. Not just in 1 part of my code but in multiple places. This has the effect that my player respawns 1 to 4 times instead of the 1 instance I want. Also picking up ammo sometimes gives me up to 4 times the amount of ammo it should.
Anyone know what could trigger this issue?
This is a part that has this issue
void OnTriggerEnter2D(Collider2D col)
{
Vector3 colPos = col.gameObject.transform.position;
Quaternion colRot = col.gameObject.transform.rotation;
// get reference to sprite renderer
SpriteRenderer sr = this.transform.gameObject.GetComponent<SpriteRenderer>();
//It can destroy players
if (col.gameObject.tag.Contains("Player"))
{
if (gameObject.name.Contains("Lava"))
{
soundEffect("FallInLava");
}
if (gameObject.name.Contains("Explosion"))
{
//Debug.Log("Mine Hit: " + gameObject.name + " by " + col.gameObject.name);
col.gameObject.GetComponent<ShotPlayer>().Hurt(col.gameObject.tag, playerNum, false);
}
else
{ col.gameObject.GetComponent<ShotPlayer>().Hurt(col.gameObject.tag, 0, true); }
if (setNewSprite && (sr.sprite != newSprite)) { sr.sprite = newSprite; }
}
//It can destroy pickups
else if (col.gameObject.name.Contains("Pickup"))
{
if (gameObject.name.Contains("Lava")) { soundEffect("FallInLava"); }
Destroy(col.gameObject, 0);
//If it's a mine we want to see explosions!
if (col.gameObject.name.Contains("Mine"))
{
GameObject explosion = Instantiate(explosionPrefab, colPos, colRot) as GameObject;
soundEffect("Explosion");
explosion.GetComponentInChildren<HostileTriggerDetection>().playerNum = 0;
Destroy(explosion.gameObject, 2f);
}
else
{
GameObject pickupAnimtion = Instantiate(pickupPrefab, colPos, colRot) as GameObject;
soundEffect("destroy pickup");
Destroy(pickupAnimtion.gameObject, 2f);
}
}
//It can destroy Destroyable Obstacles
else if (col.gameObject.tag.Contains("DestroyableObstacle"))
{
if (gameObject.name.Contains("Lava")) { soundEffect("FallInLava"); }
col.gameObject.GetComponent<OnDestroyAnimation>().DestroyIt(gameObject.name);
}
}
Thanks for the help guys!