Jump to content
  • Advertisement
  • 09/29/19 02:19 PM

    Unity
    3 Ways Unity Addressables Will Save Your Game

    General and Gameplay Programming

    Ruben Torres

    [This post was originally posted with its original formatting at The Gamedev Guru's Blog]

    If you've been following me, you will probably know my interest in Unity Addressables. That is for a reason.

    3-Ways-Addressables-Will-Save-Your-Game-

    Unity Addressables is a powerful Unity package that upgrades the way you and I have been tackling some of the most important challenges in Game Development: efficient, pain-free content management.

    When managing your game assets, it's hard to keep good standards that prevent our project from becoming a disgusting pile of mess. A big issue there is the coupling between the different responsibilities of our asset management systems.

    The way we store the assets in our project has way too much to do with the method we load them, and later use them.

    For instance, you may decide to store an innocent sprite in the Resources folder. This, in turn, will force Unity to build the player in a way that that sprite is put into special archive files. And the fact that it was put there, will corner you into loading it through the Resources API.

    Things get messy quicker than you can realize!

    One choice, multiple long-term consequences.

    A good system will prevent you and me from easily making sloppy mistakes like that. A great system will be that, and also easy to learn and use.

    With Unity Addressables, we separate the asset management concerns. Our goal is to remain flexible and to keep our project maintainable.

    Here are 3 proven ways Unity Addressables will help you and your games:

    RAM.jpg

    1. Reduce Your Game's Memory Pressure

    When you publish your game, you'll be required on most platforms to specify the minimum hardware specifications your players must meet to buy and play your game.

    The math is easy here: the more hardware power you demand, the fewer will buy your game. Or, seen from another perspective, the better memory management you do, the higher the amount of content and fun you can offer in your game.

    Unity Addressables helps you in this regard enormously!

    To give you a brief idea, converting this kind of code:

    public class CharacterCustomization : MonoBehaviour
    {
        [SerializeField] private List<Material> _armorVariations;
        [SerializeField] private MeshRenderer _armorRenderer;
    
        public void ChangeArmorVariation(int variationId)
        {
            _armorRenderer.material = _armorVariations[variationId];
        }
    }

    Into this other one:

    using UnityEngine.AddressableAssets;
    
    public class CharacterCustomizationV2 : MonoBehaviour
    {
        [SerializeField] private List<AssetReference> _armorVariations;
        [SerializeField] private MeshRenderer _armorRenderer;
    
        public IEnumerator ChangeArmorVariation(int variationId)
        {
            var loadProcess = _armorVariations[variationId].LoadAssetAsync();
            yield return loadProcess;
            _armorRenderer.material = loadProcess.Result;
        }
    }

    Will bring you these results:

    Unity-Addressables-Memory-Gain.jpg

    Easy gains I'd say.

    -> Read more on Unity Addressables for better memory management in Unity Addressables: It's Never Too Big to Fit (opens in a new tab)

     

    Controller

    2. Sell Your Next DLC - Quick and Easy

    The fact that Unity Addessables gives you full control over how, when and where to store and load your game assets is incredibly useful for implementing and selling Downloadable Content.

    Even if you are not thinking of releasing DLCs any time soon, just by using Unity Addressables in your project, you will have done already a big chunk of the work ahead.

    Other approaches for selling DLCs, such as Asset Bundles, are a very deprecated way of doing the same thing but at a much higher cost. Maintaining a well-functioning Asset Bundle pipeline is painfully time-consuming and requires a high degree of expensive expertise.

    There are many ways you can approach implementing DLCs in Unity, but for starters, this is a good starting point:

     

    public class DlcManager : MonoBehaviour
    {
        // ...
        public IEnumerator TryDownloadDlc()
        {
            if (_hasBoughtDlc && _dlcDownloaded == false)
            {
                var operationHandle = Addressables.DownloadDependenciesAsync("DLC-Content");
                while (operationHandle.IsDone == false)
                {
                    _progressText.text = $"{operationHandle.PercentComplete * 100.0f} %";
                    yield return null;
                }
            }
        }
    }

    You get the idea.

    Why would you say no to selling more entertainment for your players at a fraction of the cost?

    Time.jpg

    3. Reduce Your Iteration Times

    Using Unity Addressables will reduce the time wasted waiting in several areas.

    Tell me, how frustrating is it to be blocked for half a minute after pressing the Unity play button? And it only gets worse if you deploy your build on another platform, such as mobile or WebGL. This all starts adding minutes and minutes to your iteration times. It gets old so quickly.

    I don't like waiting either.

    But do you know what I like? Unity Addressables, my long-awaited hero. This is how Addressables will help you:

    A) Reduced Build Size

    Your game has a lot of content, I get it. Gamers love enjoying content. Developers love creating content.

    That doesn't mean, however, that every single asset you produced has to be included in the build your players will install. In fact, you should remove as much as possible.

    Players want to start playing ASAP. And they're not happy when your game steals 2GB of their data plan and 30 minutes of their gaming time. They'll just keep downloading Candy Crush kind of games that install well under 50MB.

    One strategy is to include only the assets needed to run your game up to the main menu. Then, you can progressively download the rest of your content in the background, starting, of course, downloading the first level of your game.

    It's also neat to realize that your deployment times during development will be much faster. You'll be able to iterate more times each day; this benefit quickly adds up in the long term.

    Unity Addressables - Reduced Build Sizes

    Unity Addressables - Reduced Build Sizes

    B) Reduced Load Times

    We, both as game developers and as players, hate waiting. Waiting takes us out of the zone and before you realize it, it is time to go to bed.

    Unity is working hard towards reducing the time it takes us to start playing our games, both in the Unity Editor and in the games we distribute.

    But not hard enough.

    Things look promising in the future, but not without side effects. Avoiding domain reloads in Unity 2019.3 looks promising, but as of today that's still in beta and not everyone can profit from it.

    In the mean-time, we can do better than just being frustrated.

    Let's say you're working on a medieval game. Several months ago, you implemented armor types for your game. You did a pretty damn good job and generated over 100MB of content.

    At some point, it was time to move on and right now you're working on something else, let's say sword fighting.

    Realize that, every time you press the play button to work on your features, you are loading an insane amount of data coming from all the already developed features, and loading this data takes a massive amount of time. You press play to test your sword fighting animations, and you spend 5 seconds waiting due to loading the armor features you implemented.

    The time wasted in loading is mostly spent on I/O (Input/Output), because memory bandwidth is expensive. And, on top of that, your CPU has to process it. You, as a developer, pay this time penalty while developing in the Unity Editor. But your players pay it as well in the games you are distributing.

    Knowing how big of a deal this can be, let's ask ourselves: which shortcuts can we take here?

    It turns out that Unity Addressables can help us here in two ways.

    1. Unity Addressables will reduce your Players' Loading Times

    We can alleviate some of our players' pain.

    Keeping indirect references to our assets instead of direct references will drastically improve your loading times.

    By using indirect references (AssetReference), Unity will not load everything at once but only what you tell it to. And more importantly, you have direct control over when that happens.

    2. Unity Addressables will reduce your Unity Editor Iteration Times

    How much do you know about the play mode script in the Unity Addressables Window? The play mode script defines how the Unity Editor should load the content marked as Addressable.

    With Packed Play Mode selected, Unity will directly load your pre-built addressable assets with little to no processing overhead, effectively reducing your Unity Editor iteration times

    Just do not forget to build the player content for this to work

    Unity Addressables - Build Player Content

    Unity Addressables - Build Player Content

    What if you applied these strategies to your most demanding content?

    4. Extra: Are You There Yet?

    It is true. Unity Addressables is very helpful. But this package will help only those who want to be helped.

    After reading how Addressables will help you producing better and selling more to your players, you probably want to start with it right away. However, starting in this new unknown area may be challenging.

    To make the most of your chance, answer these questions first:

    • Where are you standing right now? Are you just starting, or are your skills production-ready?
    • When to use indirect references, when to use direct references?
    • What's the bigger picture?
    • What is your next logical step?

    → Take this short quiz now to test your answers ← (opens in a new tab)

    Quiz.jpg



      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
  • Game Developer Survey

    completed-task.png

    We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a $15 incentive for your time and insights. Click here to start!

    Take me to the survey!

  • Advertisement
  • Latest Featured Articles

  • Featured Blogs

  • Advertisement
  • Popular Now

  • Similar Content

    • By intenscia
      mod.io is an cross platform mod service created by the team behind ModDB.com and IndieDB.com. It can be integrated in-game using the  REST API, C/C++ SDK or engine plugins (if available) Unity and Unreal Engine are ready to use with other engine plugins in development.
      Features include:
      Platform agnostic (support 1 click mod installs on Steam, Epic Games Store, Discord, GOG, itch.io and even consoles in the future) Clientless (mod.io has no other dependencies and works behind the scenes in your game) Embeddable web app UI, so you can integrate your mod community anywhere Powerful search, filtering and tagging of mods Moderation and reporting systems built-in Steps to getting mod.io integrated:
      Add your game to our test environment or production Read our API documentation for an overview of how mod.io works Choose an Engine Plugin, API or SDK to integrate mod.io into your game and mod making tools Ready to launch? Add your game to our production environment then let's discuss promoting your release Need help? Our team is available on Discord to assist and our getting started guide has more information for you  
       
      Benefits of using mod.io:
      mod.io offers the same core functionality as Steamworks Workshop (1 click mod installs in-game), plus mod hosting, moderation and all of the critical pieces needed. Where we differ is our approach to modding and the flexibility a REST API offers. For example: 
      Our API is not dependent on a client or SDK, allowing you to run mod.io in many places such as your homepage and launchers Designing a good mod browsing UI is hard, our plugins ship with a UI built in to save you a lot of effort and help your mods stand out We don’t apply rules globally, so if you want to enable patronage, sales or other experimental features, reach out to discuss Our platform is built by the super experienced ModDB.com team and is continually improving for your benefit Your community can consume the mod.io API to build modding fan sites or discord bots if they want Large studios and publishers:
      A private white label option is available to license, if you want a fully featured mod-platform that you can control and host in-house. Contact us to discuss.
      Find out more:
      Visit mod.io | About us | Add your game | Chat on Discord
      These screenshots are from our Unity plugin:




    • By Ruben Torres
      [The original post with its original format can be found here]
      Players want to play, they don't want to wait. Help them buying your game: reduce your game's download size with Unity Addressables Hosting. And a year later? Offer them a DLC based on, guess what? Addressables.

      Picture your potential player on a Friday afternoon.
      Your player has just left behind a hard week with long working hours. Their wife or husband is gone to their family's country house for the weekend along with the kids. The perfect time to go home, order pizza and browse through Steam with the wallet at hand.
      With or without kids, with or without partner, we all had these awesome weekends.
      Just videogames, please.

      So your player comes across your newly released game in the Steam shop. They see all the effort you put into creating polished content.
      No need for convincing, they hand in their credit card details and buy two copies of your game. One for theirself, another for their friend / brother / sister.
      You get your 19.95 bucks, twice. Both users happily start installing the game.
      But wait...
      A wild Steam installation pop-up appears.

      The remaining installation time suddenly exploded to 12 hours
      What, 12 hours for over 30GB? What the #*@! is in this game?
      I'm not wasting my weekend on this shit, I'm out!
      What happens afterward is not uncommon.
      Your ex-player requests a full refund and purchase instead the next game in their wish-list.
      One of the pain points for players is the waiting time wasted on downloading all the bytes of the whole game and start playing. People do not have that much time. Nothing will burn a hole in your wallet faster than an angry player.
      Do you need to include in your installation package all these assets that are spawned in the level 5 of your game? Chances are, you don't.
      Players will need a couple of hours to play through the initial content of your game. Use that to your advantage
      The idea is simple.
      Provide the minimum content possible in your game installation package and download the rest while playing the initial levels of your game.
      Can you picture your player ready to play in a mere minute after purchasing your game? How different would the reviews be compared to the ones commonly found with huge games?




      Ideally, your game's download size should be below 100MB.
      But how?
      This is what you will get by the time you're done implementing the information of this article:
      Ridiculously tiny installation sizes A new Amazon S3 bucket to host your content online Upload Unity Addressable Assets to S3 through the Unity Editor Download the Unity Addressable Assets from the S3 bucket in your player builds A high-five from your happy players
      Fox / Via mashable.com
      Level 1 Developer: "Storage is cheap, anyway"
      We started developing our game a few months ago and we have big plans for it.
      You and I worked endless hours into creating highly polished content.
      Not only that, we saw some great offers in the Unity Asset Store, so we bought several asset packs at heavily discounted prices.
      Now our game is full of content our players will love to play through. Those Sci-Fi modular parts, the exploding particle systems, the punchy soundtrack.
      It's all gorgeous. 
      And heavy.
      And slow to download.
      Now your Android APK is well over 2GB, so you need to start messing with expansion files, which adds another good week to your efforts. But it's fine, we all have time here.
      Or maybe you're publishing on Steam, so you can be at 30 GB, no problem. You just need a few hours for uploading it. And players? It's ok, people have a fast connection nowadays.
      So we released our game. Some players reported some bugs, so we make a 5-minute fix and we go through all the long process again. Build, wait for hours, upload to stores, wait for hours.
      And our players? They just re-download the whole thing again. Wait for hours, then start playing.
      It's not a big deal.
      Only that you are not recovering all the time you wasted on this previously. And a great deal of your players will stop downloading your game once they see how many hours they have to wait. That only gets worse with each update. Did I mention refunds?
      We can do better than this, now that we have the tools.
      Let's upgrade our skills to Level-2.

      Level 2 Developer: Unity Addressables Hosting
      Welcome to Unity Addressables.
      This package will allow you to efficiently manage your game assets. That, my friend, includes online distribution. For an introduction on this topic, visit my previous article on Unity Addressables Benefits for your game.
      These are the steps you and I will be following in the article:
      Set up an Amazon S3 Bucket for online distribution Mark our content as Unity Addressable Assets for online distribution Upload our content to the cloud Profit from tiny installation sizes (and others) Like granny said, a 2D sprite is worth a thousand times:

      Unity Addressables Hosting with Amazon S3 - Steps
      Let's start with...
      1. Setting Up a Free Amazon S3 Bucket
      It's our lucky day. Amazon offers a free tier for their S3 service.
      That means, we're going to host our content for free. The limitations for their free tier is mostly storage space and the number data transfers. At the moment of writing this, you can store for free up 5GB and perform 20,000 GET and 2,000 PUT requests, but do double check it in the official site of AWS Free Tiers.
      What we are going to do here is to create an account for AWS so we are ready to upload our game content for further distribution.
      You and I will do this as fast as possible. No need to waste time in detail. No BS.
      Setting up Amazon S3 Hosting for Unity Addressables
      1.1. Create AWS account
      Navigate to the AWS Management Console and click on Create a Free Account.

      Enter your e-mail and bla bla bla. That will take you roughly a minute.
      Be aware that you'll need to give them your credit card info to verify your identity.
      1.2. Choose AWS Plan
      Unless you're going pro right from the start, we want to evaluate this in our game first.
      So, after confirming your account, choose the basic plan.

      1.3. Create your first S3 bucket
      After a few minutes, your account will be activated (you'll get an e-mail). Then, sign in to your new console and open the S3 service panel:

      You are now located at the S3 control panel.
       
      Now we are ready to create the bucket like shown below (change your bucket name and region!):



      Leave the permissions set to public for now, you'll have the chance to tweak them in the future.
      Your S3 bucket for Unity Addressables is now ready, congratulations!
      That was the most tedious step.
      The next step is a piece of cake: time to get your Unity Project to produce downloadable assets.
      Summary:
      Use the AWS Management Console to create a Free Tier S3 Bucket For starting, assign public permissions to your S3 Bucket Alternatively, use another storage service based on the spreadsheet in the Resources Pack
      2. Unity Addressable Assets for Distribution
      Finally, we made it to Unity. That whole S3 process was getting old.
      I will assume you have some content marked as Addressable in your game. If that's not the case because you are new to this, don't worry, I have you covered with the previous Unity Addressables Tutorial I wrote.
      I'll show you the steps to get content uploaded in your newly created AWS S3 Bucket. We will do so based on a project I created for this purpose.
      Instead of following the whole story, you can also skip the line, get access to the code now and read later.

      Unity Addressables - Profile Settings
      A. Addressables Profile Configuration
      The way to start is to tell Unity where to load remote assets from.
      That we achieve by tweaking our Addressables Profile Configuration. In the Addressables main window, click on:
       Profile: Default → Inspect Profile Settings.
      This will redirect you to the settings we need to tweak.
      Here is a collection of funny toys you can play with, but for our purposes we just need to focus on the Profiles section.
      We want to make sure we set the Addressables RemoteLoadPath field to the correct URL.
      We form the RemoteLoadPath URL by concatenating our S3 Bucket URL with the Unity variable [BuildTarget], like below:
      https://YOUR-BUCKET-NAME.s3.YOUR-REGION-NAME.amazonaws.com/[BuildTarget] E.g. https://thegamedevguru.s3.eu-central-1.amazonaws.com/[BuildTarget] The [BuildTarget] variable is left on purpose so Unity fetches in run-time the right assets for each of the platforms we build for. Android assets will be packed differently from Standalone, so each of these platforms will require a different directory.
      The way I found my S3 Bucket URL is by uploading a random file; if you then navigate to its details, you'll see the base URL of your file and hence your bucket.
      B. Addressable Asset Groups Configuration
      So, we just told Unity where to load the remote assets from through the RemoteLoadPath variable.
      Great. What is left is to tell which assets should be loaded remotely. Easy.
      Go over the heavy assets you want to be downloaded remotely and mark these Assets as Addressable. In our case, it's the skybox materials. Open the Unity Addressables Window and assign these assets to Addressable Asset Groups. If you are just starting with Addressables, assign them to a single group for now; e.g. Skyboxes. Eventually, you'll want them to be grouped in a way that makes sense (check my Level-3 guide on Unity Addressables Tutorial for more info). Navigate to the Addressables Group inspector settings by clicking on the group and make the following adjustments: BuildPath is set to RemoteBuildPath LoadPath is set to RemoteLoadPath You can see a graphical breakdown of this entire process below.

      Asset Groups for Unity Addressables Hosting

      Unity Addressable Asset Group Settings for Network Delivery
      We now have our skybox content assigned to a group that will be downloaded by your players in run-time.
       Summary 
      Set RemoteLoadPath to the base URL of your web hosting provider Append the [BuildTarget] variable into RemoteLoadPath  to differentiate multiple platforms Assign your Unity Addressable Assets to a group and tweak its settings to use the remote paths so it'll be downloaded from your web hosting provider  

      3. Uploading Content to Amazon S3
      All our settings are now in place. What about uploading our content to S3?
      This is a simple two-step process:
      Build player content. Upload it to S3. Building Addressables Player Content is straightforward. Open the Addressables main window and press the button that does just that. This will cook the assets for the current platform your editor is in. 

      Unity Addressables: Build Player Content
      The output content will be stored in the path dictated by the RemoteBuildPath variable you happened to see early in the Unity Addressables Profile Settings. If you didn't modify it, it's likely to be in a subfolder of your project called ServerData.
      The second step involves navigating to that directory and dropping its contents into the website of your S3 bucket, as you can see just below:

      Unity-Addressable Assets - Upload to S3
      There you have it, it's that simple.
      However, this can quickly become tedious. It's a very manual task that could easily be automated. I did just that so now uploading all my assets takes the press of a button inside Unity Editor.
      To upload your Unity Addressable Assets directly from the Unity Editor, check my Unity Addressables Hosting Resource Pack at the end of the article.

      4. Downloading Assets from Amazon S3
      This is the part we all were waiting for. You now have a game you can distribute that is significantly smaller. The remaining part is launching it and watching it download the assets on demand!
      If you want to make sure these assets are being effectively downloaded, delete the data from your S3 Bucket, disable the caching option in your Addressable Asset Group Settings, rebuild the content and your player. If you launch it, you should see a few error messages pop up, as you can see below.

      Unity Addressable Assets Download Error
      If you followed this tutorial on Unity Addressables Hosting, chances are, you will be totally alright
      By now, the asset groups you marked to be remotely downloaded are hosted in S3 and Unity knows how to fetch them.
       

      The Gamedev Guru's S3 Upload Tool
      Level 3 Developer: Unity Addressables Hosting Resource Pack
      By now you should have your first Unity Addressables Hosting experiment up and running.
      You learned how to build player content specifically to target downloadable content.
      That's great, but there's more than just the basics. To help you further, I prepared a Free Unity Addressables Hosting Resource Pack just for you.  This bundle contains:
      A spreadsheet comparing different hosting alternatives to the pricey S3 An extension to upload your Unity Addressable Asset to Amazon S3 directly from the Editor The source code of this project; see it for yourself Newsletter access with exclusive free content Level up your skills. Download your free Resource Pack now.

       
    • By XenahE
      Hi there, 
      I am new to this forum and wanted to say hi first of all. 
      Secondly, I am in the process of creating a vertical 2d shooter using the assets I am creating on photoshop and illustrator. I want to put a scrolling parallax in the background to give the illusion that the player is moving forward (similar to Skyforce Anniversary) but I am not sure how best to create the graphics in terms of the document size etc. I have used a scrolling parallax before using a 3D game object in unity and wrapping a background to it. This works fine for a repeating background but I would like mine to change throughout the level. 
      Has anyone got any experience with doing something like this?
      Thanks in advance 
      Xe
    • By RoKabium Games
      The red hued resources you can find in SAMA is mostly on the pink and brown side of red, but the Quarky is as bright and deep red as it comes!
    • By Ruben Torres
      [This article was originally posted at The Gamedev Guru's Blog]
      I normally do not share my past struggles, but this topic deserves it. What to do when you lose hope with Unity UI?
      I still remember that weekend, about five years ago...
      I spent the entire weekend worried about all the technical debt I was accumulating over the months in one of my projects. I had done things too quickly, without really understanding them. Clearly enough, that had to stop working at some point.
      The thing is, I owed my clients results but I had no idea how to bring them. That morning though, I said to myself: Rubén, this is enough. Stop the excuses. You are becoming a professional today.
      So, I decided to gather every single resource I could find about user interfaces in Unity, because that was the biggest hurdle I was dealing with for several weeks. I read forums, best practices, Unite videos, read all blogs I could find on that topic and did my own research.

      Did you ever experience this feeling of slowly getting overwhelmed by technical debt? It accumulates over time and someday you either give up or decide to crush it. In my case, it was the later.
      You probably heard that optimizing UI in Unity is challenging. Or, if lucky, you know it from first-hand experience. Yes, Unity UI is a powerful tool and I love it. However, its mightiness can quickly transform into a deadly weapon if it falls into inexperienced hands. And so were my hands back then.
      If I had to confess anything to you today, it would be this: I wished I had had a solid foundation on Unity UI before I designed the UI of several games.
      It is SO easy to do it wrong, SO easy to get frustrated. In my opinion, there's something even easier than that. That is, for your client to ask you to do over-hours to get your shit together.
      In my experience in the professional sector, companies do not want developers who design poorly optimizable interfaces and leave the tuning task to experienced programmers. They rather want developers who create visually stunning interfaces, but also performant.
      And even in the indie development scene, where would you choose to spend your time on? Bringing fun to your players, or spending hours clicking through the profiler to find bottlenecks?
      In my opinion: no matter your role, you should understand basic Unity UI design principles. But this takes time and project experience. You might not have any of these.
      Hopefully, I can help you there.
      Today, I will give you one of my most powerful tools:
      The Guru's UI Development Diagram
      As usual, I'd like to start with the Level 1 Developer construct
       
      Level 1 Unity UI Developer: UpdateBatches & Layout Spikes in Unity UI
      Level 1 Unity UI Developer: free-style UI
      This is where we all start: free-style design, free-style results.
      I used to import sprites with whatever settings. Then, I would add them as images everywhere with no predefined criteria. And so I ended up with an unstructured hierarchy full of components that I didn't need. I used the wrong systems for the wrong reasons.
      Overlapping UI elements, a motherload of batches, profiler spikes. Those are all common.
      Do I have anything against this?
      Partially. I think it is great to play around and to make mistakes. Breaking and repairing help learning.
      But if you want to do this for a living, at some point you might want to level up your skills and embrace professionalism.
      This becomes unacceptable in the games industry, especially in Virtual Reality. If you do this in VR you will turn players into patients.
      Such a chaotic Canvas hierarchy structure could look like this:

      Level 1 Unity UI Developer: Unstructured Unity UI Hierarchy
      You do a lot of nesting, you use auto-layout components everywhere and there is a lack of rules.
      At some point, someone will ask you to optimize your UI. That could be your players, your boss or even your own pride.
      But you might not be ready for this. You might be caught off-guard having other tasks on your plate. And UI development is daunting at the beginning.
      The reason for its complexity lies in the amount of factors it involves. Leaving the visual appeal aside, you can say that the way you work with Unity UI will have a big impact in three critical hardware pieces: the CPU, the GPU and the developer theirself.
      If you are lost, it's good, because...
      I am about to show you something cool
      Let's level up as a developer!
       
      Level 2 Unity UI Developer: The Guru's UI Development Diagram
      Level 2 Unity UI Developer: The Guru's UI Development Diagram
      Here we are with a Venn Diagram. I decided to call it The Guru's UI Development Diagram.
      There we see three big chunks related to Unity UI Optimization: CPU, GPU, and Developer. Those are the main resources you will have to spare when developing UI.
      I want to give you a short overview before we start digging into the topics.
      You pay the CPU toll mainly when generating and submitting batches of UI. You can think of them as UI components, such as images. The more of those you have, the more strain you will put in your processor.
      The turn for the GPU. You pay the GPU resources mostly in concept of overdraw. This means, stacking layers of graphics on top of each other.
      Lastly, the developer's pain is paid in time. You spend time every time you design or maintain your UI. Unity offers you some tools to make it easier for you, e.g. auto-layout helpers.
      The cost of the three components rely mostly on you, but they sometimes counteract each other. It's very challenging to perform in every aspect, unless you are very experienced and you have the right tools.
      Eventually, you will get there.
      I would like you to have a closer look at the attached Guru's UI Development Diagram.
      You might be confused. That's alright because we are going to cover each section separately. You will get to understand all of it.
      For now, you only have to understand one thing: in the end, it will be up to you to find the balance between the three variables in your game.
      Before we start with each component, have a look at these general rules:
      The easier you want the UI design workflow to be, the less performant your UI will be. If you want more GPU performance, you will have to focus on finely tweaking graphical elements and avoid element stacking. For more CPU performance, you will need to reduce the amount of graphical elements present in the hierarchy. Let's move on, I can't wait to show you the CPU side of Unity UI Optimization!
       
      Level 2 Unity UI Developer: The CPU
      Level 2 Unity UI Developer: The CPU
      In my opinion, this is very simple.
      The golden rule is:
      Every time you add a UI component in your scene, you are adding CPU overhead
      Each component increases the CPU cost for the following reasons:
      RectTransform calculation: this is pretty much free in simple canvas hierarchies. However, your CPU will have a harder time if you are using auto-layout components to ease your UI design workflow, such as vertical layout groups and such. The issue with those is that most RectTransforms present in the hierarchy will now depend on each other, so the calculation becomes more complex. Vertex generation: the GPU understands vertices, thus those must be provided by the CPU. Vertices must be generated based on the entire canvas hierarchy of the involved RectTransform elements. The vertices depend as well on the specific type of UI element you added (images, texts). Under this category, we also include the cost for the CPU to add other per-vertex attributes such as colors and UVs. Dynamic batching: because draw calls are expensive, Unity does its best to dynamically batch as many of them as possible.
      Think of this as combining a large number of small groups of vertices into a single, huge group of vertices. Because... would you rather go to the supermarket ten times to bring an apple each, or go just once and grab them all together?
      Batching is, however, an expensive operation for the CPU which increases with the amount of UI elements you have. Draw call emission: finally, the generated batches must be sent to the GPU. These graphical processing units are very picky with the data formats they accept, so the CPU has to make extra work to pack them in a way that they like. This is expensive, yes. But luckily for us, Unity is kind of smart and caches the canvas so these expensive processes do not happen in every frame.
      Just as I brought you good news, I will give you the bad ones: this cache is super easy to break.
      Changing almost any attribute of any UI element will break the cache of your canvas. If that happens, we go through most of the process again. These changes, by the way, trigger what is called a canvas rebuild.
      I'll give you some examples of the breaking changes: scaling, positioning, rotation, color, image swapping, animations and more.
      After exposing the basics, I want to conclude with three practical observations:
      The more elements you have in your Unity Canvas, the more CPU overhead you will have on each canvas rebuild. Avoid any kind of changes in UI to avoid canvas rebuilds. If needed, then put dynamic elements in different canvases. Canvases are either static or dynamic. Design accordingly.  
      Level 2 Unity UI Developer: The GPU
      Level 2 Unity UI Developer: The GPU
      Now is the turn for the friendly Graphical Processing Unit, don't you think?
      The GPU is the piece of hardware that makes us fall in love with games. We owe them so much. What about showing it some affection? Well, we can...
      By treating it well.
      But guess what? UI can make the GPU pretty upset. Especially mobile GPUs, where it is relatively easy to be memory-bound. To put it simply:
      In mobile, there is a massive reason UI is expensive: overdraw!
      Overdraw happens when we render the same pixel multiple times per frame. And this is soooo easy to achieve with Unity.
      Every time to add a Unity UI Image, you are commanding your GPU to draw a full rectangle, rendering every single pixel inside that rectangle. And it does not matter if the pixel you are drawing is transparent, it will cost you still.
      That means, I advise you to be careful with the transparent regions of your sprites!
      This has some implications for you. If you add 10 full-screen images, then you get 10x overdraw. As my grandmother used to say, WTAIWYG! (What You Add Is What You Get).
      Stacking of layers on top of each other will slowly enrage your GPU. It will add milliseconds to it, which is a crime in VR games where your budget could very well be under 13ms.
      I do not want to get too technical in this post... but I can't just help it! Some day you will be having a delicious coffee break conversation with your colleagues and you might feel tempted to drop a few intellectual lines. If that's the case, say this one aloud:
      UI Overdraw is expensive in mobile because you devour the precious memory bandwidth of the device and this is further worsened by the alpha blending happening internally
      You'll make some jaws drop.
      The key lesson is easy: avoid stacking UI elements on top of each other and you will be fine 
      GPU cost mainly comes from stacking graphical layers on top of each other. Avoid these. Reduce the space UI takes in screen to reduce GPU cost. Implement sprite atlasing to improve CPU and GPU performance.  
      PRO TIP #1: Sprite Atlasing (opens in a new tab)
      PRO TIP #2: Opaque UI Shading (opens in a new tab; Advanced)
       
      Level 2 Unity UI Developer: The Developer
      Level 2 Unity UI Developer: The Developer!
      I am afraid we often under-estimate the effort required to design, implement and especially maintain optimized user interfaces in Unity.
      Surely, Unity improved in this area during the last few years and now it is easier and faster than ever to create those. But this comes at a cost.
      In general, the more Unity UI extras you use, the worse your game will perform.
      The auto-layout helpers are especially expensive. Unfortunately, they are the most helpful. For instance, I find Vertical Layout Groups especially handy when designing responsive UI. These neat scripts help you organize your elements in a manner that is structured and therefore visually appealing.
      The problem I see with those is that they incur on a big CPU cost whenever there are canvas rebuilds!
      You might be able to get away with UI helpers if your UI is static 99% of the time, but the frame it isn't, you will notice it.
      We love working with helpers, but we don't want to ruin our performance. Here's one trick you can try: keep the auto-layout helpers around while designing but disable them all just before saving your scene. By doing this, they will be deactivated for run-time players, but they already did their work for you!
      I don't want to disappoint you, so just remember that this auto-layout disabling secret will not work if your UI content is dynamic.
      At the end of the day, the more tasks you delegate to Unity, the more work your hardware will have to do.  Find your own balance here! You can start using those helpers but be ready to remove them if you have to.
      While optimizing, do the biggest gains for the buck first. Only advance in the ladder of diminishing returns if the profiler tells you that you have to.
      For instance, creating sprite atlases is easy and will bring you good fortune. Tweaking graphics to avoid transparent regions, however, is more time-consuming. Lastly, creating your own UI shaders might bring you big gains but at a big cost.
      Remember, saving a few microseconds in your game might not be worth if it costs you weeks of your life-time and your application does not need it. This should not be taken as an excuse to never care; optimizations in the future are more expensive than in the present.
      Profile before you optimize Keep profiling Go for the biggest gains for the buck first  
      Level 3 Unity UI Developer: The Guru's UI Development Diagram
      Level 3 Developer: The Sweet Spots
      From the Venn Diagram, you might see several sweet spots where you could find yourself in: Fine-Grained UI Development, Coarse-Grained UI Development, Massive PP and Balance.
      They sounded quite obscure to me at the beginning, but then, with time, it all started to make sense to me. Experience brought understanding.
      What I still hold true is that, the more tools you know, the better. This is the main way I am able to recognize the subtle patterns in all problems. And, when you recognize the heart of the challenge, you know which tool to take out of your toolbox.
      Nothing will help your team more than having a developer possessing both a high-level overview of UI and an eye for detail.
      A Level 3 developer would confidently answer important practical questions that only come through experience. I can think of a few that any client could ask you:
      Here's a UI architecture for you. How performant is it? What are 3 alternatives I have to optimize this user interface? Can you show me numerical proof?
        You see, I prepared a few Unity examples for you.
      The examples you will have access to illustrate each of the UI optimization methods I propose.
      Not only that, I analyzed them all so you can feel safe the information is accurate.
      Because... do you know what comes after speaking out of our gut feelings? Speaking with certainty, based on real experience.
      So, are you serious about becoming a Level 3 Unity UI Developer?
      ---> Grab Now the Level 3 Guide from my Blog Post.
×

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!