A few questions about what Rick puts in what script

Prior to this lecture there was a challenge to “Implement Heath and damage system for attackers and projectiles”. This I did and it all worked out nicely, however there naturally are some differences to what Rick then does.

For example:

  • I did not create a separate health script, as there was already an attacker scrip attached to the attacker lizard object, so I added the health stuff in that script (Mostly because I forgot it was on Ricks list).
  • I put the OnTriggerEnter2D in the attacker scrip and not in the projectile script.

Basically I did it like we did in Laser Defender.

As I said it works, but I am unsure if it will cause problems later.

I want learn as much as possible and therefore I don’t really want to copy Rick 1 to 1.

using UnityEngine;

public class Attacker : MonoBehaviour

{
    float currentSpeed = 1f;
    [SerializeField] int health = 100;
   
    void Update()
    {
        transform.Translate(Vector2.left * currentSpeed * Time.deltaTime);
    }

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

    private void OnTriggerEnter2D(Collider2D collidedWith)
    {
        DefenderShot defenderShot = collidedWith.gameObject.GetComponent<DefenderShot>();
        if (!defenderShot)
        {
            return;
        }
        ProcessHit(defenderShot);
    }

    private void ProcessHit(DefenderShot defenderShot)
    {
        health -= defenderShot.GetDamage();
        Debug.Log(health);
        defenderShot.Hit();
        if (health <= 0f)
        {
            EnemyDeath();
        }

    }
    private void EnemyDeath()
    {
        Destroy(gameObject);
        //To be iomplemeted
        //DeathVFX
        //DeathSFX
        //AddToScore
    }
}
using UnityEngine;

public class DefenderShot : MonoBehaviour
{
    
    [SerializeField] float shotSpeed = 2f;
    [SerializeField] int damage = 30;
   
    void Update()
    {
        transform.Translate(Vector2.right * shotSpeed * Time.deltaTime);
    }

    public int GetDamage()
    {
        return damage;
    }

    public void Hit()
    {
        Destroy(gameObject);
    }

}

Hi Karsten,

Does your solution work? If so, keep it. In many cases, there are multiple ways to make something work in Unity, and Rick cannot show all of them.

In this course, we follow the single responsibility principle, one of the most important OOP principles. That’s why we created a separate Health class.

Personal opinion:
I am all in for going off limits and do things differently, but when it comes to the basic rules and principles, I always try to follow them, because they will help me in the long run in a variety of ways.

Thank you again for your reply.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms