I have a Unity asset that switches output buses at runtime. Unfortunately someone has reported to me that this switching is causing large spikes in CPU usage:
The code that’s running during that spike looks like this: SwitchOutputBus.cs · GitHub
Basically this is doing:
- Unlock previously locked bus
- Lock new output bus
- Switch the channel output to the new bus
Is there anything wrong with this approach that might be causing the high CPU usage?
The CPU spike you’re observing is likely due to the call to Studio.System.flushCommands()
on line 52 combined with the use of Studio.Bus.lockChannelGroup()
- probably as a result of the combination of flushCommands()
blocking the calling thread, and the system potentially taking some time to create/retrieve the bus’ ChannelGroup when lockChannelGroup()
is called.
Instead of flushing commands, I’d recommend polling Studio.Bus.getChannelGroup()
for the Channel Group asynchronously using a coroutine or task, and seeing whether that reduces or resolves the CPU spike.
1 Like
Thanks for the response. Flushing commands blocking the thread makes sense.
Rather than locking and polling I’m thinking about locking a set of buses at startup and keeping them locked for the entire lifetime of the script. That way I can always switch instantly between buses in that set.
Is that a sensible/reasonable way to do it?
If you’re alright with there being time upfront where you have to wait for all the Bus’ Channel Groups to be created, then yes, this sounds entirely reasonable.