OnCollisionEnter2D not working, Again!
Hey guys, I ran into an issue today regarding OnCollisionEnter2D. My objective was to have an enemy ship receive damage and die when an oncoming bullet hit them. I have both the bullet and the enemy ship have a rigidbody2D and a box collider2D. They are also both left as static and I made sure the simulated check box was checked. Take a look at this class, it is the enemy object. I have three methods, a death method to keep destroy the object, a damage to modify the instance variable for the health, and the OnCollisionEnter2D which uses the two other methods.
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour
{
int health;
// Use this for initialization
void Start ()
{
health = 100;
}
void damage(int dmg)
{
health = health - dmg;
}
public void death()
{
if (health <= 0) {
Destroy (gameObject);
}
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Bullet")) {
Destroy (other.gameObject);
damage (50);
Debug.Log (health);
death ();
}
}
}
none of them must be static. How does the bullet move?
Yes, no static here. Your code looks correct. Can you post screenshot of the two object components?. You can try to set a breakpoint inside the OnCollisionEnter2D() method to see what happen there.