- Home /
OnTriggerEnter2D & OnCollisionEnter2D not working
I have a problem with OnTriggerEnter2D & OnCollisionEnter2D. It does not seem to detect the collision and fire off the command. I am making a top-down space shooting game have added 2d colliders and rigidbody2ds to all my ships. However, even after reading different answers and adapting my code to be similar, it still will not work. The code for the player's ship is:
using UnityEngine;
using System.Collections;
public class ControlScript : MonoBehaviour {
public GameObject bullet;
public GameObject bulletTwo;
void Update () {
rigidbody2D.velocity = new Vector2 (Input.GetAxis("Horizontal") * 10, rigidbody2D.velocity.y);
if (Input.GetKeyDown (KeyCode.Space)) {
Instantiate(bullet, new Vector3(transform.position.x - 0.5f, transform.position.y + 1.0f, transform.position.z), Quaternion.identity);
Instantiate(bullet, new Vector3(transform.position.x + 0.5f, transform.position.y + 1.0f, transform.position.z), Quaternion.identity);
}
}
void OnTriggerEnter2D (Collider2D other) {
Debug.Log ("T");
Destroy (gameObject);
}
void OnCollisionEnter2D (Collision2D other) {
Debug.Log ("C");
Destroy (gameObject);
}
}
The debug logging "c" & "t" is to see whether oncollisionenter2d is working or ontriggerenter2d. However, none of the log anything at all and don't destroy the player's ship. I have placed a box collider2d and rigidbody2d but still not working. Could someone please help? Thank you.
EDIT: The player's inspector window is as so:
The bullet prefab's inspector window is like this:
Oops, collider wasn't trigger and rigidbodies not kinematic, nut still not working. Scripts are definitely in place.
Even after editing, it's not working. Collision layer matrix is set so that the layer all the ships and bullets are on should interact with other objects on the layer.
Try saving the project and scene after using the matrix.
Same issue here. Tried a lot of different things to no avail.
Answer by GSGregory · May 06, 2021 at 10:31 PM
I could be wrong, but I believe the bullet should have a collider as well.