- Home /
OnTriggerEnter being called twice
So, I'm starting to play with Unity3D. I'm trying to make a double shot for my "Space Shooter" project.
Anyway, I've set a script for the bullets that have a function OnTriggerEnter. The bullet prefab is set to isTrigger and everything is working properly.
There's a litte problem though: The function makes a call to a function that updates the score. And, because the two bullets hits the object at the same time, it gets called twice.
I've searched for a solution and I couldn't find anything that worked. I could make a variable "numberOfHits" and make decreases on it, but I think it's not a good solution.
Here's my script:
private var isCollision : boolean = false;
function OnTriggerEnter(other : Collider){
//Check for astroid
if(other.gameObject.tag == "enemy" && !isCollision){
isCollision = true;
//Reset the position of the enemy
other.GetComponent(scriptAstroid).ResetEnemy();
//Create the explosion on impact
if(explosion){
Instantiate(explosion, transform.position, transform.rotation);
audio.PlayClipAtPoint(fxSound, transform.position);
}
//Tell scene manager that we destroyed an enemy and add a point to the score
sceneManager.transform.GetComponent(scriptSceneManager).AddScore();
//Destroy the bullet
Destroy(gameObject);
}
}
On the update function, I reset the isCollision variable to false again. But, because the two bullets hits the enemy AT THE SAME FRAME, it doesn't matter.
What do you guys suggest? Thanks in advance.
You can make the enemy call the AddScore function inside its reset function. If it only resets once, it will only add the score once. If it resets more than once, then you may need some sort of enemy manager that tracks the current active enemies.
Answer by g8minhquan · Oct 17, 2014 at 06:24 AM
If you want your Enemy only receiving 1 bullet hit, then put the isCollision bool check in the Enemy, not the bullet.
Ok, this worked man.
I have already changed the collision detection to the astroid. OnTriggerEnter is still called two times, but the function to AddScore is called just one time.
Thanks.
You're welcome. If it solved your problem, please accept the answer
Your answer
Follow this Question
Related Questions
Making my Text fade in on a trigger 2 Answers
Spawn Point Problems 1 Answer
My if statements are not working [major noob] 2 Answers
Trigger Script Not Firing 4 Answers