Game lags when loading AudioClip from Resources

Hello,

I’m trying to load an AudioClip resource at runtime using Resources.Load<>(). It’s an mp3, a few minutes in length. Loading and playing works fine, but when I call the Load function, the game will hit a lag spike of about 300-500ms. So far I have only tested this in the editor.

I have also tried using Resources.LoadAsync() in an attempt to amortize the lag, but Unity only takes 2 frames to load the resource anyway, and the lag is unchanged.

Preloading the audio is an option, but I’d rather avoid it. When I load them at runtime, I don’t care if it take an extra 1/2 second before the audio can play, as long as there’s not lag.

The code is quite simple, essentially:

ResourceRequest request = Resources.LoadAsync<AudioClip>("audioclip");

If I leave it in, I get lag. If I comment it out, I don’t. I’m not even trying to play it. Admittedly there’s a lot of other stuff going on in my code, so there may be an interaction somewhere I’m not aware of, but my guess is there isn’t.

Has anyone else run into this problem or found a solution? Any help would be much appreciated.

EDIT: I’m selecting @Sisso’s answer because it’s pretty comprehensive. For me the specific solution was to mark the assets as “Streaming” in the editor, instead of “Decompress on Load,” which is the default option.

First you need to have sure that it is the problem (and not a symptom), for example, a lot of use of CPU/Disk/Memory but you only notice when try to use a little more. Could be a lot of stuff, for example, the unpacked audio use so much memory that cause operation system to swap :stuck_out_tongue:

Try to switch the audio file, put some println to triple check if it is not loading multiples times and test into a new fresh project to have sure that is not everything else.

Debuging is a art and take a lot of times, some time is easy to go directly to the workaround :stuck_out_tongue:

Now the Profiler is available in free version, it is a good start.

You can debug the problem mixing between audio bitrate quality (repack mp3), format (switch to ogg or even wav). In general case is a trade off between file size (disk usage), unpackage size (memory usage) and processor usage (unpack process). If you game use to much cpu and no disk, very small compaction is the solution, it use a lot of disk but few cpu to unpack.

Add the asset as reference in scene to pre-load is the easy start. If can’t do it (like memory limitations in mobile), the @smallbit solution is a good one.