Jump to content
  • Advertisement
  • 10/29/19 08:32 PM

    Unity
    Unity Addressables Migration: Music to my Ears (Part 1)

    General and Gameplay Programming

    Ruben Torres

    Just one more song...

    Those famous last words of a videogame musician convincing a programmer to add the last audio track to the game that was about to be released.

    What could possibly go wrong?

    I'll tell you: that last song added a mere water drop to a glass that was about to spill.

    And effectively, it spilled.

    These extra 10MB added by the song were needed when Bobby received an SMS from his girlfriend asking him to do the laundry.

    And so the Operating System decided to take its memory back. The evil OS killed the game Bobby was playing for the last two hours.

    And you know what was the funny part? The savegame got corrupted.

    Do you know what our friend Bobby did?

    I'll tell you what he didn't do.

    He did not buy a more powerful device.

    Instead, he furiously flipped the table that was in front of him. Only that the table was made out of glass.

    There's something Bobby did before cleaning all the shards from the floor. He promised to himself to do all he could to prevent this from happening to other users.

    Bobby went to the app store and wrote the most famous 1-star review in history. People emotionally connected so well with him that his review got incredibly upvoted. So upvoted, that it surpassed and eclipsed all 5-star reviews.

    And indeed, no more crashes ever happened to any other user, because new players held their fingers off the install button.

    What could Bobby have done instead?

    Well, Bobby could have messaged the developer instead to send him the article you're about to read.

    Unity-Addressables-Migration-AudioClip-T

    You've seen the potential benefits of Addressables and you want to give it a shot in your game. But there're so many possibilities! Where to start with your Unity Addressables Migration? Here's an option for you: Music.

    [The original blog post with its formatting can be found at Unity Addressables Migration for Music]

    Lowering your memory consumption to reduce crashes? Increasing performance? Reducing loading times?

    No matter what your goal is. If you want to start using Addressables right away, you'll experience the Unity Addressables Migration process.

    Migration is nothing else than moving from where you are to the place you want to be.

    In the context of this series, we'll be migrating the asset management system you're currently using over to an Addressables-based one.

    Yes, even if you're not aware of what an asset management system is, you're already using one by default: Unity's direct references.

    As I'll show you later, you can say you have a direct reference to an asset every time you assign this asset from the Project view to a field of a component in the inspector. For example, assigning a sound to the field AudioClip of an AudioSource is considered as having a direct reference to that sound.

    But what's the crack with these direct references?

    This should be your main concern: Unity will automatically have directly referenced assets loaded in memory. And there's nothing you can do about it other than not having that direct reference present.

    What a burden.

    The alternative is using indirect references.

    And the benefit?

    With Addressables you choose when and whether to load the asset you're pointing to. Particles, prefabs, textures, music, you name it. By doing this you'll reduce memory consumption, increase performance and gain other several huge advantages such as the possibility of shipping DLCs etc..

    In this blog post you and I will start the level-up journey and migrate one of the most common types of content in a beautifully crafted game: soundtracks.

    Quick Navigation (opens in new tab)

    Unity Addressables Migration: Requirements

    Level 1 Developer: Directly Referenced AudioClips

    Level 2 Developer: Indirectly Referenced AudioClips

    Unity Addressables Migration: Where do we go from Here?

    laptop-coffee.jpg

    Unity Addressables Migration: Requirements

    This one is easy, unless you're stuck to an old version of Unity, that is.

    You'll want to install the Unity Addressables Package for Unity 2019+.

    I posted a step-by-step guide on my Unity Addressables Tutorial blog post, but you don't have to go through it now. This is what you want instead:

    1. Open Unity and go to Window → Packages to open the package manager interface
    2. Scroll down and look for the Addressables Package
    3. Install it

    Press start to begin our quest

    Level 1 Developer: Directly Referenced AudioClips

    We'll start our quest on leveling up by migrating one of the easiest assets: music.

    I'll assume you have a global MusicPlayer object laying around your project. That guy has an AudioSource component attached to it so we can play the music of our choice through its AudioClip component.

    Generally speaking, we also have a script that contains a list of tracks to play, so we play them after another.

    Below you see an example of a direct reference hidden in plain sight.

    Direct Reference to an AudioClip

    Direct Reference to an AudioClip

    Coming back to our topic, you really don't want to have too many direct references to different AudioClips at once. That would mean, they are all loaded in memory, even though we are potentially playing only one song.

    Having long AudioClips can and will increase the memory usage of your application along with your loading times.

    You'll be stealing from your memory budget instead of spending it on the actual cool stuff.

    Either you have to be very careful with the direct references you use or, even better, you can use Unity Addressables to profit from indirect references.

    Naturally, you and I are going for the second approach here.

    Level 2 Developer: Indirectly Referenced AudioClips

    Let your performance explosion begin.

    Start the migration by navigating through our music tracks in the Project View. In my case, my audio clips are called 8-bit-music-track-1, 8-bit-music-track-2 and so on.

    With each AudioClip selected, we then tick their Addressables checkbox in the inspector.

    Unity Addressables Migration: AudioClip import settings

    Unity Addressables Migration: AudioClip import settings

    These AudioClips are now part of the Addressables family and they're ready to be indirectly referenced.

    About our next task...

    With great power comes great responsibility

    These indirect references will not manage themselves!

    We'll create a neat MusicPlayer script that will play each music track one after another. We'll add this script to a new game object of the same name.

    So we go over to type some basic code.

    01: namespace TheGamedevGuru
    02: {
    03: public class MusicPlayer : MonoBehaviour
    04: {
    05:     [SerializeField] private AudioSource _audioSource = null;0
    06:     [SerializeField] private AssetReference[] _soundtracks = null;
    07:     private int _playingSoundtrack = 0;
    08: 
    09:     IEnumerator Start()
    10:     {
    11:         while (true)
    12:         {
    13:             var currentOperationHandle = _soundtracks[_playingSoundtrack].LoadAssetAsync();
    14:             yield return currentOperationHandle;
    15:             var newAudioClip = currentOperationHandle.Result;
    16:             _audioSource.clip = newAudioClip;
    17:             _audioSource.Play();
    18:             
    19:             yield return new WaitUntil(() => _audioSource.isPlaying == false);
    20:             
    21:             _audioSource.clip = null;
    22:             Addressables.Release(currentOperationHandle);
    23:             
    24:             _playingSoundtrack = (_playingSoundtrack + 1) % _soundtracks.Length;
    25:         }
    26:     }
    27: }
    28: }

    This sample script does quite a few simple things.


    First, in line 5 we keep a (direct) reference to an audio source component. This component is purely behavior, it has (almost) no data associated with it, so a direct reference is the way to go.

    The referenced AudioSource  component will play the audio clip of our choice later on.

    In line 6 we keep an array of indirect references to sound tracks that will be played sequentially. Each element of this array corresponds to a track to play while the user goes through their mission. What is critical here is to notice that we're using AssetReference to hold indirect references to the sound tracks. If we were to use direct references, we'd have an array of AudioClip instead.

    But using indirect references this way will prevent Unity from automagically loading them all and skyrocketing your and my memory consumption and loading times.

    Unity Addressables Indirect References to AudioClips

    Unity Addressables Indirect References to AudioClips

    In line 7 we just keep an integer to know which soundtrack index we're currently playing. Bookkeeping and such.

    Then, in line 9, we tell Unity to spawn a coroutine to handle the main loop of our logic to play music. There are several ways of doing the same without coroutines, but I'll stick to clarity.

    What's that in line 13?

    There, my friend, is where all the magic juice happens.

    We command Addressables to load the AudioClip that our integer number points to. As this takes some time, we wait for it to finish in line 14 before proceeding.

    And when the loading is done? We play it! The resulting AudioClip can be found in the next line under the Result field of the handle we waited on.

    We then assign the newly loaded clip in line 16 and proceed to play it.

     

    BAM!
    What was that?

    That was an explosion of sound

    Your player starts spilling cold sweat and feels the adrenaline rush

    All of this thanks to the creepy music you just started pushing into their ears

     

    But all tracks sadly come to an end. So we wait for it to finish in line 19 and then we unassign that AudioClip from the AudioSource.

    Finally, line 22 releases the data we previously loaded through the Addressables API.

    All clean like a (well-taken care of) baby.

    In line 24 we point to the next AudioClip to load and play in the next iteration of the loop. Rinse and repeat.

    Hey, we got our digital jukebox up and running in a matter of minutes. Not bad.

    But what's the benefit?

    Now your game will be super performant

    Your game will hold only one track in memory at a time

    (instead of 4+)

    This solution scales just well, period.

    As a side note, AudioClip's Load Type field can be set to streaming. This gives you the false impression that you'll not profit from Addressables.

    I'll make the argument that both streaming and compressed in memory give you memory gains, but this happens at the cost of increasing your CPU load. Addressables will give you the maximum performance such as in Decompress On Load while keeping memory overhead low, as you'll only load the music you're currently playing.

    Junctions for Multiple Unity Editor Instances

    Unity Addressables Migration: Where do we go from here?

    We barely scratched the surface of Addressables.

    But now your music composer has now some new toy to play with. That's all that matters.

    In the next post, we'll be migrating something more.. how to say, challenging. But I'm not spoiling it yet.

    If I arose your curiosity on the topic, have a look at the Addressables Tutorial I wrote for you.

    Till then, I'd be happy if you commented below and shared your experiences with Addressables with the community.

    Ruben

     

    Edited by Ruben Torres



      Report Article


    User Feedback


    There are no comments to display.



    Create an account or sign in to comment

    You need to be a member in order to leave a comment

    Create an account

    Sign up for a new account in our community. It's easy!

    Register a new account

    Sign in

    Already have an account? Sign in here.

    Sign In Now

  • Advertisement
  • Advertisement
  • Latest Featured Articles

  • Featured Blogs

  • Advertisement
  • Popular Now

  • Similar Content

    • By N1H1LU5_k
      Greetings. Thank you for opening this thread. Long post ahead. I am a High School student trying to get into game development. I would like to ask you a set of questions, but I think giving a context first will be the best. So, this is what's happening:
       
      In recent time, about 3 weeks ago, I started learning how to use Unity Game Engine and Blender. I always loved to draw and design all kinds of weapons, armors but also levels (unfortunately, all of those are on paper only, FOR NOW, of course) and when I started to think about how to apply this trait of mine, I concluded I could try creating a game. Since it's only been three weeks, my game-making skills are extremelly poor (as expected). Fast forward to yesterday. We were supposed to pick up a topic for our graduation thesis which we will hand in closely to our school-leaving examinations in year 2021. There is a TON of stuff to choose from. As long as it is part of IT, it's fine. And I chose to make a game. Well, it's more of a one level of a game in my case. More students before me have taken this topic and passed totally OK with Flappy Bird-style game they made. They were satisfied with it. I wouldn't be. I want this game to be best possible, that is why I also want to start working on it as soon as possible. In fact, I am starting right now, but I figured it would be better to ask here first. I have roughly 17 months to make a game worthy of passing. Of course, it could be some Flappy Bird. But I want to go further. Excuse me if this all sounds stupid, but I simply would not be satisfied with just any game I would make. I am well aware I won't be able to make a game like Battlefield alone, that there is a ton of people and budget behind such games. But I want it to be as best as possible.
       
      Now, my question is: What kind of game would I be able to make in this time of 17 months ? You have probably rolled your eyes after this question, don't worry, I understand how subjective the answer is. But I will at least try to state some metrics that can help with answer. I believe I have some fundamentals of programming, willing to learn the language needed (I believe in this case it's c#), I will be hooked on creating, animating and further improving 3D assets as needed for sure. I am able to dedicate at least 2 hours every day, a lot more so on weekends. I have to prepare for school and I also work, so that would be 2 hours of time on workdays right now. I would be able to get music and voice samples for characters in the game. 
       
      Here is my current plan. Please, if you see this as unreal to make in my deadline, tell me about it. I want to make one level of a FPS shooter, kinda sci-fi game with approximatelly 4-5 cutscenes and a small bossfight at the end of the level. Graphical quality would be that of a current CS:GO. Favored play-time would be, I think, around 15-20 minutes. Map would be a destroyed urban area. I have a lot of concepts (characters, weapons, rooms and so on) already drawn and if not, envisioned. If this is not possible, what would be the best game I would be able to make in 17 months ?
       
      Thank you for reading. Please, be honest. I know my idea can sound stupid, and answer I am looking might seem too subjective, but I want to get corrected if I am wrong with all of this. I highly value any reply that will be able to help in the slightest.
       
      Until then, have a nice day.
       
    • By Trexioas Xavier
      I want to know how would i go about making a 3D line renderer, it can be either a 3D or 2D-billboard line renderer. I don't want it to be static, i would like to add vertices to the line and extend it however i want to. To give an idea of what i want it to be/look like, Think of the Gauss Gun from Half life 1 and Half Life 2. I would want to make it reflect off the walls. I know i would need to do calculations to determine how to reflect off walls, i am just asking how would i go about making a 2D/3D line renderer. Please send me some online resources i can read upon.
      Thank you for your help!
    • By RoKabium Games
      Weapons - Magnacer is the first basic weapon that your Alien has equipped from the start. It shoots single bullets with a medium range that makes moderate damage to most enemies.
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!