fiticida fiticida - 3 months ago 26
C# Question

Don't know how to use OnCollisionEnter in Unity3D

I am having problems with my method OnCollisionEnter, I dont know why it isn't working properly.

Here is my code:

void OnCollisionEnter(Collision col){

if (col.gameObject.name == "Bullet" && !bulletEnter)
{
Debug.Log(enemyLives);
enemyLives = enemyLives - 1;

if (enemyLives == 0)
{
Destroy(gameObject);
//Modificamos el GameManager e incrementamos el dinero que poseemos tras la muerte de Enemy.
GameManager.Manager.currentGold(enemyGold);
}

bulletEnter = true;


}
else if (col.gameObject.name == "OtherBullet" && !bulletEnter) {
enemyLives = enemyLives - 2;
if (enemyLives == 0)
{
Destroy(this.gameObject);
GameManager.Manager.currentGold(enemyGold);
}

bulletEnter = true;

}
}

//Cuando sale la colision lo ponemos a false, esto lo realizamos para que unicamente exista un choque con los coliders.
void OnCollisionExit(Collision col)
{
bulletEnter = false;
}


As you can see there, when the Bullet reaches Enemy the trigger should be activated but it isnt working, I am using "Debug.Log" for checking if it enters inside the methods but it doesnt.

Here I also add the picture from my inspector.

enter image description here

Answer

I created a simple scene for this and quickly found your problem. Uncheck Is Trigger property on Box Collider of your Enemy GameObject. OnCollisionEnter should now be called as expected.

Few other improvement on your code:

1.Use CompareTag instead of checking it by name. Simply change if (col.gameObject.name == "Bullet" && !bulletEnter) to if (col.transform.CompareTag("Bullet") && !bulletEnter).

2.Also, you had

void OnCollisionExit(Collision col)
{
    bulletEnter = false;
}

This is not a good logic because anything that collides with the Enemy will be considered as a Bullet. Check if it is a Bullet like you did inside the OnCollisionEnter function before setting bulletEnter to false. This will likely prevent other problems in the future.

Comments