Static event does not trigger during initial loading of scene

Currently, I am trying to instantiate a new health bar for each new gameObject with a health system. The game has 12 components with a health system script in them. However during runtime, “Before” and “After” are printed 12 times alternatingly but no “HealthSystem added” is printed. One thing to note though whenever I duplicate any of these gameObjects, the all three Debug.Logs are triggered and the HealthSystem is added and the health bar appears on screen. I just do not understand why it does not work during the initial load of the scene. Could someone explain what the problem is and maybe try to give the solution to this kind of problem? Thank you very much, I’ve struggled to find any answers online and ive been on this problem for a long time :frowning:

public class HealthSystem : MonoBehaviour {

public static event Action<HealthSystem> OnHealthAdded = delegate { };
public static event Action<HealthSystem> OnHealthRemoved = delegate { };

private void OnEnable()
{
    Debug.Log("Before");
    OnHealthAdded(this);
    Debug.Log("After");
}

private void OnDisable()
{
    OnHealthRemoved(this);
}

}

public class HealthBarController : MonoBehaviour {

[SerializeField] private HealthBar healthBarPrefab;

private Dictionary<HealthSystem, HealthBar> healthBars = new Dictionary<HealthSystem, HealthBar>();

private void Awake()
{
    HealthSystem.OnHealthAdded += AddHealthBar;
    HealthSystem.OnHealthRemoved += RemoveHealthBar;
}

private void AddHealthBar(HealthSystem healthSystem)
{
    Debug.Log("HealthSystem added");
    if (healthBars.ContainsKey(healthSystem) == false)
    {
        var healthBar = Instantiate(healthBarPrefab, transform);
        healthBars.Add(healthSystem, healthBar);
        healthBar.SetHealthSystem(healthSystem);
    }
}

private void RemoveHealthBar(HealthSystem healthSystem)
{
    Debug.Log("HealthSystem destroyed");
    if (healthBars.ContainsKey(healthSystem))
    {
        Destroy(healthBars[healthSystem].gameObject);
        healthBars.Remove(healthSystem);
    }
}

}

i would say your problem is with the script execution order, OnEnable isnt like start that is excuted after all the awakes. the awake is called just before the OnEnable, but not before all the OnEnable of all objects, you need to make the healthBarController execution order faster than the healthbarsystem script, the script orther is right now is something like this

 HealthSystem [Awake -> OnEnable(calls your events with still nothing subscribes)] -> HealthBarController[Awake (your subscrubed right now)-> OnEnable]

for changing execution order is Edit->Project Settings → Script Execution Order