Removing unnecessary health class

This may just be a personal preference, but I don’t see the Health script as being necessary. I think it adds more confusion as there’s more objects to work with and more things to link up in Unity. Also we can achieve the same result in a simpler way.

Instead of giving the attacker (enemy in my case) a Health class, I’ve just given him a _health variable. I wanted the defender to determine the damage output instead of the projectile. When the Defender class instantiates a projectile it sets the damage output. I’ve pasted my code below in case you wish to do the same.

Defender Script

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

public class Defender : MonoBehaviour
{

    [SerializeField] Projectile _projectile;
    [SerializeField] GameObject _FirePosition;
    [SerializeField] public float _attackPower = 0;

    public void Fire(float damage) {
        if (_FirePosition == null) {
            var projectile = Instantiate(_projectile, transform.position, transform.rotation);
            projectile.setDamage(_attackPower);
        }
        else {
            var projectile = Instantiate(_projectile, _FirePosition.transform.position, transform.rotation);
            projectile.setDamage(_attackPower);
        }
    }
}

Enemy Script

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

public class Enemy : MonoBehaviour
{
    
    [SerializeField] float _health;
    float _currentSpeed = 0;

    public void SetMovementSpeed(float speed) {
        _currentSpeed = speed;
    }

    void Update()
    {
        transform.Translate(Vector2.left * _currentSpeed * Time.deltaTime);
    }

    public void takeDamage(float damage) {
        _health -= damage;

        if (_health <= 0) {
            Destroy(gameObject);
        }
    }
}

Projectile Script

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

public class Projectile : MonoBehaviour
{
    [SerializeField] float _currentSpeed = 0;
    float _damage = 0;

    void Update()
    {
        transform.Translate(Vector2.right * _currentSpeed * Time.deltaTime);
    }

    public void setDamage(float damage) {
        _damage = damage;
    }

    private void OnTriggerEnter2D(Collider2D otherCollider) {

        // Reduce Enemy Health
        var enemy = otherCollider.GetComponent<Enemy>();
        enemy.takeDamage(_damage);
    }
}

Privacy & Terms