Thoughts on the Collisons FYI

For some reason that the teacher does not explain, he/she creates a method in the script DamageDealer that calls the Destroy(gameobject) without looking at health and then creates a method in the Health script that checks health and then calls Destroy(gameobject) and then asks the game run them after one another like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Health : MonoBehaviour
{
    [SerializeField] int health = 50;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        DamageDealer damageDealer = collision.GetComponent<DamageDealer>();
        Debug.Log(damageDealer);
        Debug.Log(health);

        if (damageDealer != null )
        {

            TakeDamage(damageDealer.GetDamage());
            damageDealer.Hit();
        }
    }

    void TakeDamage(int damage)
    {
        health -= damage;
        if (health <= 0) 
        {
            Destroy(gameObject);
        }
    }
}

So, the code inside the OnTriggerEnter is being asked to do is run the method TakeDamage and then destroy both objects in the collision.

At least that is what I thought, because I put the DamageDealer script on both the Enemy and the Player. When I either commented out damageDealer.Hit(); or removed the DamageDealer script from the Player, then I got the same results as the teacher.

DamageDealer goes on the bullets/lasers, not on the player or enemy. It doesn’t check health because the bullets get destroyed as soon as they hit anything and they do not have health.

Health goes on the player/enemy. It checks health because the player/enemy has health and should only be destroyed when there is no more health left.

The script calls both on collision because the bullet/laser needs to be destroyed, and the player/enemy needs to lose some health

Privacy & Terms