Search Unity

Applying DMG with missles

Discussion in 'Scripting' started by DasJonny, Oct 17, 2017.

  1. DasJonny

    DasJonny

    Joined:
    May 15, 2017
    Posts:
    32
    Hello there!
    I am not the very best at programming and just trying some things out, so this might be an idiotic question:
    I am creating a game where you are a plane, ufo or smth like that that can shoot from left to right while you have to dodge enemys missles.
    I made the missles as GameObjects (not sure how to use raycasts properly) and now i got to a point i don`t know how to solve.
    I want to set the dmg the missles does to the enemys in a script that lays on the missle itself (i want to make it able to manipulate a single missles dmg etc. in the end). Now when I hit an enemy i use OnTriggerEnter2D on the missles script.
    I wonder how this non-syntactic code has to be written in C# code:

    if(Enemy hit)
    {
    hit_enemy_life = hit_enemy_life - missle_dmg
    }

    so the problem I have is to transfer the hit enemy`s life to the script

    And another question: Would it make more sense to do (just the same) script, but on the enemy itself instead of the missle`s script?
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Try to make each object only care about itself. The missile knows how much damage it will do, and can damage anything "damage-able". What you define as "damage-able" can be as complex or simple as you want.

    For now, you can have your missile only hit objects of type Enemy. Later, you may want to make a more generic way to do damage to anything. Common ways to do that are with inheritance, interfaces, or a specific component that handles health/damage that you can add to anything.

    So for a simple example, here's what your missile could do:
    Code (CSharp):
    1. public class Missile : MonoBehaviour
    2. {
    3.     public float damage;
    4.  
    5.     // ...
    6.     // movement code, etc.
    7.     // ...
    8.  
    9.     private void OnTriggerEnter2D(Collider2D collider)
    10.     {
    11.         Enemy enemy = collider.GetComponent<Enemy>();
    12.         if(enemy != null)
    13.         {
    14.             enemy.ApplyDamage(damage);
    15.  
    16.             // destroy this missile
    17.             Destroy(gameObject);
    18.         }
    19.     }
    20. }
    So all you would need to do is add a function on your Enemy script "public void ApplyDamage(float damage)". Which will reduce the enemy's health from within the Enemy class. That will make it really easy to debug as well, because you can see and control what calls ApplyDamage and what happens inside that function, instead of things directly accessing the Enemy's health variable from all over the place.