Search Unity

[New to Unity] Dealing DMG

Discussion in 'Scripting' started by DasJonny, Nov 21, 2017.

  1. DasJonny

    DasJonny

    Joined:
    May 15, 2017
    Posts:
    32
    Hello!
    I am still quite new to programming with Unity - or programing at all.
    I have the following problem:
    For a little game i make i want to have a bullet and enemys. Enemys have HP and the bullet has an amount of DMG. Now i want to access the enemy`s life from my bullet script.
    Pseudocode should look like:

    OnCollisionEnter2D()
    {
    if (hit is an enemy)
    enemy.life -= DMG
    Destroy(gameobject)
    }


    so what i want to do is to access the enemys life from the bullet. My problem is, i don`t know how. Also there should be multiple enemys of the same type, so the dmg should only be applied to the enemy hit, i`ve had a similiar case with something else where a script affected all object of the same type.

    Can someone help? I am coding in C#
     
  2. Nitrousek

    Nitrousek

    Joined:
    Jan 31, 2016
    Posts:
    38
    Code (CSharp):
    1. private void OnCollisionEnter2D(Collision2D collision)
    2. {
    3. // good idea to check for a tag here, and skip mindless code execution if the tag differs.
    4. var enemy = collision.collider.gameObject.GetComponent<Enemy>();
    5. var dmg = 5f;
    6. if(enemy != null)
    7.     {
    8.     enemy.health -= dmg
    9.     }
    10. }
    this is assuming the enemy hit actually has "Enemy.cs" script attached, with health value to reduce.
     
    Last edited: Nov 21, 2017
    DasJonny likes this.
  3. DasJonny

    DasJonny

    Joined:
    May 15, 2017
    Posts:
    32
    Perfect! Ty. Guess this showed me how to access any Component as well =P