Okay I’ve been stuck on this for hours now, my health in my game works perfectly after 10 shots it dies but for some reason the health bar isnt connecting to the health.
Health Bar Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
public Slider slider;
public Gradient gradient;
public Image fill;
public void SetMaxHealth(int currenthealth)
{
slider.maxValue = currenthealth;
slider.value = currenthealth;
fill.color = gradient.Evaluate(1f);
}
public void SetHealth(int currenthealth)
{
slider.value = currenthealth;
fill.color = gradient.Evaluate(slider.normalizedValue);
}
}
Enemy Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class EnemyComputer : MonoBehaviour
{
public int maxHealth = 100;
public int currenthealth;
public HealthBar healthBar;
void Start()
{
currenthealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
}
public void TakeDamage(int damage)
{
currenthealth -= damage;
if (currenthealth <= 0)
{
Die();
}
healthBar.SetHealth(currenthealth);
}
void Die()
{
Destroy(gameObject);
SceneManager.LoadScene("Main Menu");
}
}
And the bullet script if needed
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScriptComputer : MonoBehaviour
{
public float speed = 20f;
public int damageComputer = 40;
public Rigidbody2D rb;
public AudioSource shootHit;
public AudioClip shootHit1;
// Use this for initialization
void Start()
{
rb.velocity = transform.right * -1 * speed;
}
void OnCollisionEnter2D(Collision2D hitInfo)
{
shootHit.PlayOneShot(shootHit1);
EnemyComputer enemyComputer = hitInfo.gameObject.GetComponent<EnemyComputer>();
if (enemyComputer != null)
{
enemyComputer.TakeDamage(damageComputer);
}
Destroy(gameObject);
}
}