Lots of enabling objects causes lag

In my game, when the player touches a trigger collider in a boss arena, the boss, along with many other objects get enabled using this code on the Trigger object:

bossscript.activated = true;
boss.SetActive(true);
bosshealthbar.GetComponent<Image>().enabled = true;
bosshealthbar2.GetComponent<Image>().enabled = true;
gameObject.SetActive(false);
startmusic.SetActive(false);
bossmusic.Play();

this causes lag that has about a one second delay when the player hits this collider every time the player goes into the room, even during builds.

Does anyone know a way to fix this or a better way to enable these objects?

For debugging purposes, it might help to comment-out some of these lines to see if some operations are taking longer than others so that you can focus on those. The Profiler may also help see which one is taking the most time. Do you do anything expensive in the OnEnable scripts on any of the objects you are enabling?

If I had to guess, maybe loading the music for the first time is causing the hiccup. You can try setting the audio file to “streaming” instead of “Decompress on Load” to see if that help.

You could get the references to the bosshealthbar and bosshealthbar2 in Awake so that you don’t need to call GetComponent on the fly, but I doubt this will have too much impact.

Use the Profiler to see what takes how much time.

All the components (and their children) of an inactive object will run their OnEnable method btw. The code in these methods should be just as lightweight as Update code.