- Home /
I want to add a health bar to existing code
I already have code that handles the enemy's health what I want to do is incorporate a health bar system that would be managed by the current code. If anyone could please help me with this I would really appreciate it I've checked all the other related topics to this issue but all I see is separate code that would be on there own, what I need is something that is used within my current code.
Please someone help.
Here is my code:
using UnityEngine; using System.Collections;
public class DamagableObject : MonoBehaviour {
public bool m_Invincible = false;
public float m_MaxHealth = 100f;
[SerializeField]
public float m_Health = 100f;
public DecayingObject m_DeathEffectPrefab;
public DecayingObject m_RemainsPrefab;
public string m_DeathAnimation;
/*public virtual float health
{
set
{
if (!m_Invincible || m_Health < value)
{
m_Health = value;
}
if (m_Health <= 0)
{
Death();
}
else if (m_Health > m_MaxHealth)
{
m_Health = m_MaxHealth;
}
}
get
{
return m_Health;
}
}*/
public virtual void DealDamage(float val, Vector3 pos, Vector3 normal)
{
if (val > 0f && !m_Invincible)
{
m_Health -= val;
if (m_Health <= 0)
{
Death();
}
}
}
public virtual void Heal(float val)
{
if (val > 0f)
{
m_Health += val;
if (m_Health > m_MaxHealth)
{
m_Health = m_MaxHealth;
}
}
}
public float GetHealth()
{
return m_Health;
}
protected void Start() {
bool error = false;
if (m_MaxHealth <= 0)
{
Debug.LogError("Max health can't be less than or equal to 0");
error = true;
}
if (m_Health > m_MaxHealth || m_Health <= 0)
{
Debug.LogError("Invalid health range expected 0-" + m_MaxHealth + " got " + m_Health);
error = true;
}
if (error)
{
Debug.Break();
}
}
protected void Death()
{
if (m_DeathEffectPrefab != null)
{
Instantiate(m_DeathEffectPrefab, transform.position, transform.rotation);
}
if (animation != null && animation[m_DeathAnimation] != null)
{
animation.CrossFade(m_DeathAnimation, 0.5f, PlayMode.StopAll);
if (m_RemainsPrefab != null)
{
StartCoroutine("WaitForDeathAnimation", animation[m_DeathAnimation].length);
}
}
else
{
if (m_RemainsPrefab != null)
{
Instantiate(m_RemainsPrefab, transform.position, transform.rotation);
}
Destroy(gameObject);
}
}
protected IEnumerator WaitForDeathAnimation(float time)
{
yield return new WaitForSeconds(time);
Instantiate(m_RemainsPrefab, transform.position, transform.rotation);
Destroy(gameObject);
}
}
I got this code from a friend and altered it I just need help with this health bar issue
Answer by Anxo · Jan 06, 2012 at 10:11 PM
Create a var that holds a prefab of a health bar for the enemy prefab within your code, then just have its width be controlled by the var that holds that enemies health.
I'm a little new to this would you be able to give me an example?
Your answer
Follow this Question
Related Questions
GuiTexture above 3D objects 1 Answer
GUI healthbar 3 Answers
Detect if any GUI is being displayed on-screen? 1 Answer
percentage health bar 1 Answer
Shrink GUI 1 Answer