I created in object Health Bar into my canvas and attached my HealthBar script to it:
Now I want to reference this Health Bar into my Monster that i’m spawning but it doesnt let me insert it into the public reference:
Here is the code of my HealthBar script :
public class HealthBar : MonoBehaviour
{
public Slider slider;
public void SetMaxHealth(int health)
{
slider.maxValue = health;
slider.value = health;
}
public void SetHealth(int health)
{
slider.value = health;
}
}
and here is the code of my MonsterManager:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonsterManager : 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);
healthBar = GameObject.FindObjectOfType<HealthBar>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
TakeDamage(20);
}
}
void TakeDamage(int damage)
{
currentHealth -= damage;
healthBar.SetHealth(currentHealth);
}
}
It does find the HealthBar object as I can call it’s fuctions. I also tried many things like GetObect witht he name…
Any help?