#Architecture to avoid allocation

1 messages · Page 1 of 1 (latest)

lapis path
#

So I have created a kind of wrapper around the Unity AudioSource called MicroSource. It is used in the custom audio system MicroAudio which basically uses pooling for AudioSources and gives back MicroSource wrapper for easier control of the AudioSources and some nice QoL features.

PROBLEM: I allocate MicroSource object/class for each sound which is not very good. I could do pooling for it also but user can store reference to the MicroSource and use it later, which means it can be used when new sound effects have already taken it. I though about adding flag "DontReleaseOnComplete" and then user manually releases it back to pool when its done with the sound but seems like there are better and more elegant solutions to this problem.

So basically if anyone has any suggestions how to resolve this problem?

green jackal
#

You can change your MicroSource wrapper into a struct which only contains an unique ID, like a uint, and a reference to the MicroAudio that created it (or if it's a static class, just the ID is enough).

MicroAudio would generate a unique ID for every audio it creates, just a simple increment counter is enough, and store which IDs correspond to which pooled AudioSources, like in a Dictionary. When an audio source finishes and you return it to the pool, you also remove the ID from the Dictionary, severing that connection.

MicroSource would contain all the properties and methods you would normally have, but instead of having a reference to the AudioSource, it only has its ID, which it gives to MicroAudio to try to get its audio source. If the audio source was returned to the pool, the ID will be expired and MicroAudio won't give it the audio source.

lapis path
midnight thorn