- Home /
Health Code, Damage and Healing
Hello I need help figuring out code that will make my health bar go down when i'm in collision with an enemy and make it go up when i'm in collision with my "healing pad". Everything i try results in errors so heres my code, i do have the health bar working it just doesn't go up or down it just stays at where i set it(in the code its set to 41 as a test and it worked). My damage script doesn't work and idk why So if anyone could help me figure out damage and healing it'd be really great using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class HealthBar2 : MonoBehaviour {
public Image ImgHealthBar;
public Text TxtHealth;
public int Min;
public int Max;
private int mCurrentValue;
private float mCurrentPercent;
public void SetHealth(int health)
{
if (health != mCurrentValue)
{
if (Max - Min == 0)
{
mCurrentValue = 0;
mCurrentPercent = 0;
}
else
{
mCurrentValue = health;
mCurrentPercent = (float)mCurrentValue / (float)(Max - Min);
}
TxtHealth.text = string.Format("{0} %", Mathf.RoundToInt(mCurrentPercent * 100));
ImgHealthBar.fillAmount = mCurrentPercent;
}
}
public float CurrentPercent
{
get { return mCurrentPercent; }
}
public int CurrentValue
{
get { return mCurrentValue; }
}
private void Start()
{
SetHealth(41);
}
}
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class DamageSource : MonoBehaviour { private bool _isCausingDamage = false;
public float DamageRepeatRate = 0.1f;
public int DamageAmount = 1;
public bool Repeating = true;
private void OnTriggerEnter(Collider other)
{
_isCausingDamage = true;
PlayerController player = other.gameObject.GetComponent<PlayerController>();
if(player != null)
{
if (Repeating)
StartCoroutine(TakeDamage(player, DamageRepeatRate));
}
else
{
player.TakeDamage(DamageAmount);
}
}
IEnumerator TakeDamage(PlayerController player, float repeatRate)
{
while (_isCausingDamage)
{
player.TakeDamage(DamageAmount);
TakeDamage(player, repeatRate);
yield return new WaitForSeconds(repeatRate);
}
}
private void OnTriggerExit(Collider other)
{
PlayerController player = other.gameObject.GetComponent<PlayerController>();
if(player != null)
{
_isCausingDamage = false;
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
Your answer
Follow this Question
Related Questions
Health below zero but shows negative numbers 1 Answer
how to make enemy damage player? 1 Answer
Calling a variable from one script to another 1 Answer
Help w/variables 0 Answers
Health Bar going 0 right away 1 Answer