Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Can't calculate enemies health

Discussion in '2D' started by Kaiz0ku, Dec 7, 2014.

  1. Kaiz0ku

    Kaiz0ku

    Joined:
    Oct 28, 2014
    Posts:
    6
    Hello everyone !

    I am very new in Unity and in order to create my sidescroller i have been getting help from the 3DBuzz tutorials.
    But they do not show how to do melee damage so i have tried to combine their code with mine... which has resulted to some issues.

    so i have a character which holds a sword. The sword has a box collider on it.
    I have a box which i consider the enemy and have given it Health , a Health bar and also a boxcollider.

    The Sword has a SimpleSlash scipt on it :

    using UnityEngine;
    using System.Collections;

    public class SimpleSlash : Slash, ITakeDamage
    {

    public int Damage;

    protected override void OnCollideTakeDamage(Collider2D other, ITakeDamage takeDamage)
    {
    takeDamage.TakeDamage(Damage, gameObject);

    }
    }

    -----------------------------------
    ITakeDamage Interface

    public interface ITakeDamage
    {

    void TakeDamage(int damage, GameObject instigator);



    }
    ------------------------------
    And then i have the Enemy Class

    using UnityEngine;
    using System.Collections;

    public class SimpleenemyAI : MonoBehaviour, ITakeDamage
    {

    public float speed;
    public float SlashRate = 1;
    public GameObject DestroyedEffect;
    public int MaxHealth = 100;
    private CharacterController2D _controller;
    private Vector2 _direction;
    private Vector2 _startPosition;
    private float _canSlashIn;
    public int Health { get; private set; }


    (some other methods)
    And

    public void TakeDamage(int damage, GameObject instigator)
    {

    Health -= damage;

    if (Health <= 0)
    {
    Instantiate(DestroyedEffect, transform.position, transform.rotation);
    gameObject.SetActive(false);
    }
    }
    ------------------------------------------------------------

    the problem is that once the sword collides with the enemy the Enemy immediately dissapears !
    I thought maybe the sword hits the target multiple times and Health goes immediately to zero... but no
    I tried setting the sword damage to 0 and the same thing happens ! The enemy immediately dies/disappears !

    Can you guys help me ? (sorry for posting code as text)
     
  2. Kaiz0ku

    Kaiz0ku

    Joined:
    Oct 28, 2014
    Posts:
    6
    Solved, i am an idiot. I forgot to set the Health to max health in the beginning !