Question by
unity_1806618 · Dec 02, 2018 at 10:16 PM ·
2dcollisiondestroyobjects
Help with collisions not working for no apparent reason??
I have 2 objects in my game, an invader and a spaceship. I have managed to code it so that when my player fires a bullet at an invader they will die and a visual effect is played, also when the player is touched by an invader, they lose a life and a sound effect is played but I cannot get the invader itself to be destroyed.
Here is my code for when the invader is destroyed by the spaceship firing a bullet:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour {
public int health = 100;
public GameObject deathEffect;
void Die()
{
Instantiate(deathEffect, transform.position, Quaternion.identity);
Destroy(gameObject);
FindObjectOfType<AudioManager>().Play("Impact");
}
int direction = -1; //int direction where 0 is stay, 1 up, -1 down
int top = 3;
float speed = 1;
public object GameController { get; private set; }
void Update()
{
if (transform.position.y >= top)
direction = -1;
transform.Translate(0, speed * direction * Time.deltaTime, 0);
}
public void TakeDamage(int damage)
{
health -= damage;
if (health <= 0)
{
Die();
}
}
}
Here is the code for the player losing a life when they are touched:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollisionScript : MonoBehaviour
{
public AudioSource LostLife;
public GameObject deathEffect;
void Start()
{
LostLife = GetComponent<AudioSource>();
}
void OnTriggerEnter2D (Collider2D col)
{
if (col.gameObject.tag == "Player")
{
GameObject.Find("GameControl").GetComponent<GameController>().lives -= 1;
LostLife.Play();
}
}
}
And this is the code I am trying to implement into the first chunk of code to destroy the invader
void OnCollisionEnter2D(Collision2D col){
Debug.Log("Collision");
if(col.gameObject.tag == "Spaceship")
{
Destroy(gameObject);
}
}
I have also tried using
void OnCollisionEnter2D(Collision2D col){
Debug.Log("Collision");
if(col.gameObject.tag == "Spaceship")
{
Die();
}
}
But to no avail.
Thank you for any replies.
Comment