Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by elvish_unity · Dec 09, 2018 at 05:59 PM · unity 5enemynoobhealth barhealth

Enemy Health Bar Fill (Unity2D)

So I have a Enemy. I have a enemy script with health and such, and I have a script which deals damage to the enemy, I have a healthbar with fill that is a child of my enemy i wnat it to represent my enemies health so when my enemy takes damage my health bar lowers.

Enemy Script

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 
 public class EnemyFollow : MonoBehaviour {
 
   
     
     public float speed;
   
     public float ehealth;
     
     private Transform target;
 
     // Use this for initialization
     void Start () {
 
         EnemyHealthBar = GetComponent<Image>();
        
         
         target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
 
  
         
     }
     
     // Update is called once per frame
     void Update () {
 
         transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
   
         if(Vector2.Distance(transform.position, transform.position) <= 5)
         {
             Debug.Log("Help");
         }
 
 
         
 
         if(ehealth <= 0)
         {
             Die();
             if (HealthBarScript.health < 10)
             {
                 HealthBarScript.health += 0.5f;
             }
         }
     
         
 
     }
 
     public void Die()
     {
         Destroy(this.gameObject);
 
     }
 
     void OnTriggerEnter2D(Collider2D other)
     {
         if (other.CompareTag("Player"))
         {
             Destroy(this.gameObject);
             HealthBarScript.health -= 1f;
         }
         
 
     }
 }

Script that deals damage to enemy

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 
 public class Projectile : MonoBehaviour {
 
     private GameObject triggeringEnemy;
     private Vector2 target;
     public float speed;
     public float damage;
    
     // Use this for initialization
     void Start () {
         target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
       
     }
     
     // Update is called once per frame
     void Update () {
         transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
 
         if(Vector2.Distance(transform.position, target) < 0.1f)
         {
             Destroy(gameObject);
         }
 
     }
 
     private void OnTriggerEnter2D(Collider2D other)
     {
         if(other.tag == "Enemy")
         {
             Destroy(gameObject);    
             triggeringEnemy = other.gameObject;
             triggeringEnemy.GetComponent<EnemyFollow>().ehealth -= damage;
            
         }
     }
 }
 

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Vega4Life · Dec 09, 2018 at 06:17 PM

This should give you an idea of how to deal with it. You hit the space bar, deals damage, reduces the health bar.


 using UnityEngine;
 using UnityEngine.UI;
 
 
 /// <summary>
 /// Slap this on your health bar object and link the image that has the fill
 /// </summary>
 public class HealthBar : MonoBehaviour
 {
     [SerializeField] Image healthBar;
 
     float startingHealth = 100f;
 
     // This property is the main theme here - as it updates it auto updates the health bar
     float currentHealth;
     float CurrentHealth
     {
         get { return currentHealth; }
         set
         {
             currentHealth = value;
             healthBar.fillAmount = currentHealth / startingHealth;
         }
     }
 
     bool isDead { get { return CurrentHealth <= 0; } }
 
 
     void Start()
     {
         CurrentHealth = startingHealth;
     }
 
 
     void Update()
     {
         // Just faking damage for testing so you can see how I do it
         // Your damage will be coming from somewhere else
         if (Input.GetKeyDown(KeyCode.Space))
         {
             if (isDead == false)
             {
                 DealDamage(Random.Range(5f, 25f));
             }
         }
     }
 
 
     void DealDamage(float damageAmount)
     {
         CurrentHealth -= damageAmount;
     }
 }

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image elvish_unity · Dec 09, 2018 at 06:32 PM 0
Share

I am quite new to Unity so I cannot undertand how I can apply this to my script?

avatar image Vega4Life elvish_unity · Dec 09, 2018 at 06:38 PM 0
Share

It's for you to look it over, pick out the parts you need. $$anonymous$$ore than likely you just need the CurrentHealthProperty. Copy this out and put it in your the script that has health access and health bar fill.


 // This property is the main theme here - as it updates it auto updates the health bar
      float currentHealth;
      float CurrentHealth
      {
          get { return currentHealth; }
          set
          {
              currentHealth = value;
              healthBar.fillAmount = currentHealth / startingHealth;
          }
      }


Not to be mean, but this is where you have to look over what I have, figure out how it works. Then retro fit it into what you are doing. That's the fun part of program$$anonymous$$g. You should have all the pieces to make your healthbar work. :)

avatar image
0

Answer by elvish_unity · Dec 09, 2018 at 06:55 PM

  1. I slapped on a EnemyHealthBarScript onto my EnemyHealthBars fill.

  2. The code is like this

    using UnityEngine; using UnityEngine.UI;

    public class EnemyHealthBarScript : MonoBehaviour { Image EnemyHealthBar;

      void Start()
         {
             EnemyHealthBar = GetComponent<Image>();
     
         }
     
         void Update()
         {
             EnemyHealthBar.fillAmount = EnemyFollow.ehealth;
         }
     }
     
     
    
    

` But I get an error = "An object reference is required to access non-static static member". I need a little guiding.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

189 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Enemy won't damage player C# 1 Answer

Need Help About Health,Damage 1 Answer

Health change than object health is not decreasing ? 2 Answers

Change Health of a duplicated enemeis 1 Answer

Health to come above enemy when clicked 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges