Reputation: 1
I'm trying to destroy the enemy if it's colliding with a bullet. But the OnTriggerEnter2D is not working. I've been trying to solve this and searching for answers for hours but I can't seem to find the problem.
Enemy Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyManager : MonoBehaviour
{
[SerializeField]
private Transform target;
[SerializeField]
private float speed;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("Colliding with trigger");
if (collision.CompareTag("bullet"))
{
Debug.Log("I got hit");
Destroy(gameObject);
}
}
}
Bullet
Enemy
Upvotes: 0
Views: 2622
Reputation: 1
Hello this is my first help post and 2 and a half years late... but I had a similar issue and maybe could help someone else. If you have an "Enemy" script try this. I use the word smash to avoid built in words like destroy or break.
Use this to call: within the < > place the objects "Tag" between the < > to destroy the object. Enemy in this case
collision.GetComponent< Enemy >().Smash();
In the "Enemy" script use an IEnumerator "Coroutine"
IEnumerator SmashCo()
{
yield return new WaitForSeconds(.3f);
this.gameObject.SetActive(false);
}
Call this Coroutine within the "Enemy" script: Note: animator is a reference to Unity's Animator
public void SmashEnemy()
{
animator.SetBool("smash", true); // Set the animator Bool for smash
StartCoroutine(SmashCo());
}
Add a trigger called smash to your game object. You should be able to destroy anything like this.
Note: Used Stack Overflow in the shadows for a long time, this is my first post and I would like to be corrected if I am wrong about anything thank you. Just trying to help. *Thought this was a different approach to the current answers.
Upvotes: 0
Reputation: 171
Try switch the isTrigger on the collider instead of the bullet.
Please refer also to this documentation on how to create 2d collider : how to destroy an item after collision
Upvotes: 0
Reputation: 13864
If it's an actual object that collides with another you want to use OnCollisionEnter2D
instead. Triggers are for objects that can't be collided with and you just want to know if they're overlapping.
Upvotes: 2