Home > Mobile >  UNITY 3D | Can't drag HealthBar canvas object into GameObject HealthBar reference
UNITY 3D | Can't drag HealthBar canvas object into GameObject HealthBar reference

Time:10-11

I created an object "Health Bar" into my canvas and attached my HealthBar script to it:

HealthBar Inspector

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:

Reference in object not accepting HealthBar

Here is the code of my HealthBar script :

 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:

 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);
 }

CodePudding user response:

When you say you're spawning a monster, I assume you mean you're instantiating a monster prefab into your scene.

Prefabs don't accept references to scene items, for the most part. There are was around this, but, for simplicity, let's just treat that as true.

With that in mind, the laziest way to resolve your issue is to find the health bar when the monster is spawned.

private HealthBar healthBar;

void Start()
{
    healthBar = GameObject.Find("Canvas/HealthBar");
    currentHealth = maxHealth;
    healthBar.SetMaxHealth(maxHealth);
    healthBar = GameObject.FindObjectOfType<HealthBar>();
}

While this should work for you, it would be far better to find the health bar once and cache the reference. You would do this in something like a game manager, so when your monster runs it's Start method, it can simple get the reference from the game manager.

CodePudding user response:

You cannot assign scene variables to your prefab. You can put a canvas in your monster prefab and set its render mode to World. Then, when you instantiate your monsters, you must assign the camera variable of your canvas to the game camera. I suggest you to read this:

From my experience, many world space canvases are faster than one big overlay that is constantly dirtied.

So it seems like using multiple world canvases is a good solution.

  • Related