Can't drag HealthBar canvas object into GameObject HealthBar reference

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:

200587-monsterinput.png

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?

The anwser to my problem the lack of some knowledge.

Indeed, it’s not allowed to drag UI component into Prefabs instances. The way to do around that is to create a new canvas with the image you want to add to your scene, make that canvas a World Object and then you can actually drag it.