Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Need Help with Enemy Health

Discussion in 'Scripting' started by MasouriSama, Mar 11, 2020.

  1. MasouriSama

    MasouriSama

    Joined:
    Mar 11, 2020
    Posts:
    4
    So my Problem is Currenty that i have a working healthsystem/health bar, but if i attack 1 enemy all the other ones get Damaged aswell.

    this is my scripst so far:

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

    public class HealthEnemy : MonoBehaviour
    {

    public int maxHealth = 100;
    public int currentHealth;

    public HealthBar healthBar;
    // Start is called before the first frame update
    void Start()
    {
    currentHealth = maxHealth;
    healthBar.SetMaxHealth(maxHealth);

    }


    void OnTriggerEnter(Collider _collision){

    if(_collision.gameObject.tag=="projectilefriendly")
    {
    TakeDamage(20);
    }

    void TakeDamage(int damage)
    {
    currentHealth -= damage;

    healthBar.SetHealth(currentHealth);
    }
    }
    // Update is called once per frame
    void Update()
    {
    if(currentHealth <= 0)
    {
    DestroyEntity();
    }

    void DestroyEntity()
    {

    Destroy(gameObject);
    }

    }
    }
     
  2. stephenchildree

    stephenchildree

    Joined:
    Apr 17, 2019
    Posts:
    4
    Are you instantiating your enemies into the game with another script?

    The problem could be if you're directly calling
    Instantiate(enemy,position,rotation)
    and not creating a separate instance for each enemy with
    GameObject enemyInstance = Instantiate(enemy,position,rotation)
    as directly calling it will basically link every copy of the object in the scene instead of having them be separate.

    I'm not sure if that's even relevant to your game, but your code looks fine so that's what came to mind.
     
  3. MasouriSama

    MasouriSama

    Joined:
    Mar 11, 2020
    Posts:
    4
    i already fixed it but thank u.
     
  4. davidnibi

    davidnibi

    Joined:
    Dec 19, 2012
    Posts:
    424