OnTriggerEnter and OnTriggerExit called twice despite checking it
Hi everyone,
I have read a lot of questions about this problem but i couldn't solve it yet. I have one ball with an Sphere Collider and an invisible wall to restart the ball when it passes through it (on the onTriggerExit method). The problem is that i've not been able to solve it, even with a boolean to avoid entering the method.
Code:
using UnityEngine;
using System.Collections;
public class ballRestart : MonoBehaviour
{
shootController instance;
bool isColliding;
// Use this for initialization
void Start()
{
instance = Camera.main.GetComponent<shootController>();
isColliding = false;
}
public void OnTriggerEnter(Collider col)
{
Debug.Log("TeEnter: " + isColliding);
if (!isColliding)
{
isColliding = true;
Debug.Log("TRIGGERED: "+isColliding);
}
}
void OnTriggerExit(Collider hit)
{
Debug.Log("TeExit: " + isColliding);
if (isColliding)
{
instance.initializeBall();
isColliding = false;
Debug.Log("exit");
}
}
}
OUTPUT:
As you see, it enters twice each time the ball enters the collider and twice each time the ball exits the same collider. I don't know what happens here.
Thank you.
Answer by paramburu · Jan 31, 2017 at 03:58 PM
Hi, It hardly seems like enough information. Maybe extend it with the "shootController" code and captions of your game objects.
Depending on the "initializeBall" method it could be a number of things. Translating the ball again through the collider, instantiating a second ball with a second collider or two instances of "ballRestart". The latter would account for the isColliding bool issue because each instance would have their own.
Good luck.
Here you go:
public void initializeBall()
{
GameObject aux = Instantiate(ball, initialPosition, initialRotation);
Destroy(ball);
ball = aux;
rigidBodyBall = ball.GetComponent<Rigidbody>();
audioShot = ball.GetComponent<AudioSource>();
rigidBodyBall.angularVelocity = Vector3.zero;
rigidBodyBall.velocity = Vector3.zero;
canShoot = true;
ejecutarFisicas = false;
temporizadorInicial = 0;
instanciaControladorEntrenamiento.resultado(crossbarHit);
crossbarHit = false;
}
Now it comes to my $$anonymous$$d that i had some problems trying to re-instantiate the ball to its initial point, I don't know if the way that i solved the problem is a good one.
Thank you
Hi, ball is a prefab? I don't understand because you are instantiating ball into aux, then destroying ball and then assigning aux into ball which would "overwrite" the prefab instance.
I would suggest that you instantiate the ball only once on the Start method and then reset it's transform with ball.transform.position = initialPosition and ball.transform.rotation = initialRotation.
Working with the same instance ins$$anonymous$$d of Destroying and Instantiating is also more performant.
Let me know if that works.