<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[The Unity Developer’s Handbook - Medium]]></title>
        <description><![CDATA[A collection of useful essays, tutorials, and articles about Unity. - Medium]]></description>
        <link>https://medium.com/the-unity-developers-handbook?source=rss----a8b9bd588157---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>The Unity Developer’s Handbook - Medium</title>
            <link>https://medium.com/the-unity-developers-handbook?source=rss----a8b9bd588157---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:41:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/the-unity-developers-handbook" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Goodbye MissingReferenceException! Hello, Automated Validation in Unity.]]></title>
            <link>https://medium.com/the-unity-developers-handbook/goodbye-missingreferenceexceptions-hello-automated-validation-in-unity-38bbb2fc7a1a?source=rss----a8b9bd588157---4</link>
            <guid isPermaLink="false">https://medium.com/p/38bbb2fc7a1a</guid>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Darren Tsung]]></dc:creator>
            <pubDate>Tue, 13 Jun 2017 12:52:44 GMT</pubDate>
            <atom:updated>2017-06-14T03:33:12.993Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s late on a Friday. You’ve finally found the fix for that bug you’ve been looking at all week. Code. Commit. Push. You lean back into your chair and congratulate yourself on a job well done.</p><p>Two weeks later, you realize that your fix broke a poorly tested button callback. That parameter you added to the SendHelpEmail() method had unforeseen consequences. For days, customers have been pressing the “Get Help” button, only to have nothing happen in response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*gcw1Z1l_hUxhBV-z7L9sDA.png" /><figcaption>Oops.</figcaption></figure><p>The culprit here is serialization, the way Unity saves the raw data which forms the prefabs and scenes that make up the games we know and love. It’s far too easy for a developer to delete an old asset or change a simple method and accidentally break a flow somewhere in the project, especially for bigger and more complex projects and teams.</p><p>How bad can these mistakes be? Sure, a developer might catch it after a quick editor play-through. Or maybe QA finds the bug before release. But if the bug makes it out into the wild customers will be forced to live with a broken game for days until the new build is fixed, tested, and finally approved.</p><p>If you want to ship fast and often, there has to be a better way to prevent these mistakes from happening. How can we release products with confidence?</p><h3>Enter Automated Validation</h3><p>The heart of the problem lies in understanding how Unity serializes assets. For each asset inside a Unity project, there is a corresponding .meta file. In that .meta file, there is a value named guid which is a <strong>g</strong>lobally <strong>u</strong>nique <strong>id</strong>entifier. So when Unity saves a reference to an asset like a script or a prefab, it‘s actually saving the guid of the asset’s .meta file. If the asset is renamed or moved, Unity looks for a .meta file with the same name in the same folder. If that .meta file isn’t found, Unity treats it as a new asset and all previous references are broken.</p><p>So what happens if a script reference is broken? The attached script no longer matches any guid, so the type is lost and the script instance can’t be created. Instead the inspector will show a “Missing Mono Script” notification.</p><p>But missing scripts aren’t the only thing that can break. A similar system is also used when serializing links to GameObjects or Components within a scene, except the ids are not globally unique, but unique within the scene. Whenever there is a serialized UnityEngine.Object field in the inspector, there is a corresponding drag-and-drop outlet that needs to be fill out. If a component is removed or a GameObject is deleted, the referencing fields will be broken. Since these fields are usually exposed by developers for a reason, when an outlet is broken or missing it should raise a red flag.</p><p>Lastly, there are serialized UnityEvents. They serialize both a UnityEngine.Object target and a method call, so not only can you break the target reference, but you can also break the event by changing the method.</p><p>Now we have a set of cases for the validator to catch. How do we dynamically validate the components and fields? To start off: we need to retrieve all the components. A quick breath-first-search of the hierarchy tree will visit all GameObjects, and a call to GetComponents&lt;Component&gt;() will grab their components. For every component that is null, we have a missing MonoScript!</p><p>Now that we have all the components, we need to check that all their fields are filled out. We can use <em>reflection</em> to dynamically retrieve all the fields that are public or are marked with [SerializeField]. Reflection is a powerful tool that can give you information about types during runtime. Again, if any of these fields are null then they are missing or broken.</p><p>Finally, let’s validate all the serialized fields derived from UnityEvent. At first I tried checking that the method name exists, but then realized that if there are multiple methods with the same name the arguments would be needed as well. After looking through the <a href="https://github.com/MattRix/UnityDecompiled">UnityDecompiled</a> repository, I discovered that there is more saved to the UnityEvent than is exposed in the public API. In the end, we can use reflection to expose internal functions Unity uses to validate the UnityEvent for our own use.</p><p>And that’s it! You can now build your own validator for all these different types of references in Unity. But I’ve also open-sourced my own version for those of you interested. It handles additional edge cases, allows for more complex customization on what to validate, and has an exhaustive set of unit tests to make sure it works for all cases.</p><h3>Okay, how do I get started?</h3><ol><li>Download the <a href="https://github.com/DarrenTsung/DTValidator">DTValidator</a> project from the repository <a href="https://github.com/DarrenTsung/DTValidator/archive/master.zip">here</a>. It should automatically download the latest state of the master branch.</li><li>Place the downloaded folder in your project. I recommend placing it in the Assets/Plugins directory so <a href="https://medium.com/@darrentsung/the-clocks-ticking-how-to-optimize-compile-time-in-unity-45d1f200572b">it doesn’t add to your compile time</a>.</li></ol><p>Now that DTValidator is installed in your project, you can find the validation errors by opening the DTValidator Window which is located under Window top bar menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*x02O8AyusaJvms6dABrIjQ.png" /></figure><p>Press the Validate! button to find errors in your project. You can see where the error originated from and even highlight the object in the editor. Most likely most of the validation errors are outlets that don’t necessarily need to be filled. To have the validator ignore these fields, you can mark them with [DTValidator.Optional]. See the <a href="https://github.com/DarrenTsung/DTValidator#faq">FAQ</a> for any additional questions you have on how to resolve errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*xBvSu_U1IE8WEPOPrH8iYQ.png" /></figure><p>Once you have no errors, you’re done!</p><p>However, it’s very unlikely that you’ll remember to run these tests manually, so I recommend running validation as an automated step in your build-pipeline. This is why the validator includes a set of unit tests to validate your project. You should set your build system to run unit tests for every build, with Unity Cloud Build it only takes one click!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtFJArZcp4H7KFtx0DzucQ.png" /><figcaption>Bonus points for marking your builds as failed when tests fail!</figcaption></figure><p>Now you can easily find and check new validation errors when they come up, deciding whether they are actual errors (and fixing them) or new outlets that were introduced that are optional.</p><p>I hope that <a href="https://github.com/DarrenTsung/DTValidator">DTValidator</a> helps you reduce the number of bugs that are shipped out to customers, play-testers, or whoever! If you encounter a bug or something that I didn’t think about, check the <a href="https://github.com/DarrenTsung/DTValidator#faq">FAQ</a> first, then <a href="https://github.com/DarrenTsung/DTValidator/issues">file an issue</a> if your question is not answered.</p><p><em>Interested in </em><a href="https://medium.com/@darrentsung/the-clocks-ticking-how-to-optimize-compile-time-in-unity-45d1f200572b"><em>reducing your compile time</em></a><em>? Or maybe </em><a href="https://medium.com/the-unity-developers-handbook/dont-re-invent-finite-state-machines-how-to-repurpose-unity-s-animator-7c6c421e5785"><em>using the animator as a finite-state-machine</em></a><em> instead of building your own implementation? Check out my other articles!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38bbb2fc7a1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-unity-developers-handbook/goodbye-missingreferenceexceptions-hello-automated-validation-in-unity-38bbb2fc7a1a">Goodbye MissingReferenceException! Hello, Automated Validation in Unity.</a> was originally published in <a href="https://medium.com/the-unity-developers-handbook">The Unity Developer’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t Re-invent Finite State Machines: How to Repurpose Unity’s Animator]]></title>
            <link>https://medium.com/the-unity-developers-handbook/dont-re-invent-finite-state-machines-how-to-repurpose-unity-s-animator-7c6c421e5785?source=rss----a8b9bd588157---4</link>
            <guid isPermaLink="false">https://medium.com/p/7c6c421e5785</guid>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Darren Tsung]]></dc:creator>
            <pubDate>Sun, 28 May 2017 19:09:00 GMT</pubDate>
            <atom:updated>2017-10-02T23:35:44.376Z</atom:updated>
            <content:encoded><![CDATA[<p>Finite state machines are one of the most popular patterns in game development for good reason. They can reduce complexity and create more readable programs by encouraging modular, re-usable states. While FSMs (finite state machines) fail to scale to more complex situations, they’re excellent solutions for most common-place situations like dealing with application state or making simple AI.*</p><p><em>*I won’t explain the basic concepts and use-cases of FSMs because I think there are already a lot of good articles online like </em><a href="http://gameprogrammingpatterns.com/state.html"><em>this article</em></a><em> from </em><a href="https://medium.com/u/6211394299c"><em>Bob Nystrom</em></a><em>’s book on game programming patterns.</em></p><p>There are two main approaches for creating and using FSMs: writing a quick and dirty implementation or buying an asset from the asset store to use. But there is a third option: using Unity’s built-in animator system (Mecanim).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzXyvUUYASLkQz9w__AW6w.png" /></figure><h3>Why would you use Unity’s <em>animation</em> system?</h3><p>It can seem a bit weird to reuse the animation system to create finite state machines, but the animator <em>is</em> a finite state machine. While it has animation specific features that can get in the way, the animator system does almost everything you’d want. It comes with tools for editing and visualizing the state machine during run-time. Also, it’s supported by Unity, tested by millions of developers, and any Unity animation experience you already have is applicable.</p><h4>Why not build a quick and dirty implementation instead?</h4><p>A quick and dirty implementation works well for the task that it’s designed for, but once you need to use this pattern elsewhere, you’ll find yourself re-writing the same code over and over again. The animator system can easily create different state machines with re-usable state behaviors.</p><h4>Then how about using a third-party asset?</h4><p>There are third-party assets that rival the animator system in complexity and power (like <a href="https://www.assetstore.unity3d.com/en/#!/content/14914">NodeCanvas</a>). They also have the advantage of a cleaner API because they don’t deal with animations. I’ve even <a href="https://github.com/DarrenTsung/finite-graph-machine">built my own implementation</a> that I eventually stopped using in favor of re-repurposing the animator. Because you’re going to using the animator to, well, <em>animate</em>, re-using it for state-machines means you don’t have to switch contexts between two similar systems.</p><h3>Okay, how do I start?</h3><p>First, I’ll cover the basic concepts of Unity’s Animator system (Mecanim).</p><ul><li>In Unity, you can create an asset called an <strong>Animator Controller</strong>. This is a state machine template.</li><li>There are states inside your state machine. You’re probably used to associating states with animations, but they’re actually optional if you want to create a pure-logic state machine.</li><li>To run your state machine, add a component called <strong>Animator</strong> to a GameObject and set it up with any Animator Controller that you’ve created. This is now an <em>instance</em> of your state machine.</li><li>To run logic on each state, we’ll need to create a script derived from the class <strong>StateMachineBehaviour</strong>. Once we have this new behavior, we can add it to any state inside the state machine.**</li></ul><p>You can read more in-depth about Animators <a href="https://docs.unity3d.com/Manual/Animator.html">here</a> or <a href="https://unity3d.com/learn/tutorials/topics/animation/animator-controller">watch a tutorial here</a>.</p><p><em>**Note that this works similarly to MonoBehaviours: the script receives pre-defined messages, like OnEnter, OnExit, etc.</em></p><h4>How do you use StateMachineBehaviours?</h4><p>I most commonly use states to manage the lifecycle of objects and their own behavior, using the <strong>OnStateEnter</strong> and <strong>OnStateExit</strong> messages when inheriting from StateMachineBehaviour. For example, if I want my state to listen to any game events, I usually add listeners on enter and remove them on exit. By cleaning up objects on exit, you avoid hard-to-trace after-effects like left-over game objects or zombie listeners. You don’t want your state to be affecting the game when it’s not active!</p><p>One problem that I’ve found is that OnStateExit is not called when the Animator is disabled or destroyed. So, to clean up the current state properly, you’ll need to make sure to handle OnDisable as well***.</p><p><em>***To save myself time, I’ve created a repository which I import into my game located </em><a href="https://github.com/DarrenTsung/DTAnimatorStateMachine"><em>here</em></a><em>. Feel free to use it in your own projects!</em></p><p>Let’s walk through a simple state machine that I’ve created for an enemy in my own game, <a href="https://twitter.com/hashtag/jellyquest">Jellyquest</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*M_Bo835H0ZsmbWq6dRWOiw.gif" /></figure><p>This is the angry pufferfish. He’ll rotate around slowly until he spots the player, and then he’ll propel himself rapidly in the player’s direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*-SrDav1Vsl993E_yre5CxA.png" /></figure><p>The pufferfish is a prefab configured with an AnimatorController named AngryPufferfish. There are 3 states: Aiming, PreparingToShoot, and Shooting. The pufferfish starts off in the Aiming state, which is composed of two state behaviors: <strong>RotateFacingDirection</strong> and <strong>AimInFacingDirection</strong>.</p><p><strong>RotateFacingDirection</strong> rotates the pufferfish based on a configurable speed. <strong>AimInFacingDirection</strong> figures out if the pufferfish is facing a target based on a raycast.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/786d7704a0cd65ff6d7b55a26b2e7da2/href">https://medium.com/media/786d7704a0cd65ff6d7b55a26b2e7da2/href</a></iframe><p>In the PreparingToShoot state, I re-use a state behavior named <strong>TriggerContinueAfterDelay</strong> with a parameter for how long the delay is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1d8fbe7b6d9274813fcbf60568e29a2/href">https://medium.com/media/c1d8fbe7b6d9274813fcbf60568e29a2/href</a></iframe><p>And in the Shooting state, I use a <strong>MoveInFacingDirection</strong> state behavior to move the pufferfish towards the player.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6533944b01690fde7a469086440546e9/href">https://medium.com/media/6533944b01690fde7a469086440546e9/href</a></iframe><p>By making each of these behaviors generic and single-purpose, I can tweak and re-use them in other state machines to create a variety of different enemy types.</p><h3>Awesome, anything else I should know?</h3><p>There are some common pitfalls that you should be careful of. These make more sense the more familiar you are with the animator system.</p><ul><li>Be weary of writing code that can set a trigger many times in the same frame. Because triggers are only consumed once by a transition, the trigger might get set after being consumed and persist past the current state.</li><li>OnStateEnter and OnStateExit on sub-state machines probably do NOT work as you’d expect. They are only called when hitting the entry and exit nodes of the sub-state machine. But those nodes can be bypassed accidentally by making transitions that directly go into to a specific sub-state or out to an external state.</li><li>Transition duration should probably always be set to zero. If transition duration is non-zero, the next state’s OnEnter will be called before the current state’s OnExit.</li><li>Transitions using triggers will advance to the next state in the same frame. Transitions based on other parameter types take an extra frame.</li></ul><p>TL;DR:</p><ul><li>Finite state machines are useful to manage life-cycles of objects</li><li>People either write their own state machines in code or buy a 3rd party asset from the asset store. But you can also repurpose the Unity Animator.</li><li>The Animator comes with built-in visualization, tooling, transitions, and a familiar api.</li><li>Using the Animator is awesome, but be careful of some pitfalls, get more details above!</li></ul><p><em>Interested in </em><a href="https://medium.com/@darrentsung/the-clocks-ticking-how-to-optimize-compile-time-in-unity-45d1f200572b"><em>reducing your compile time</em></a><em>? Or maybe </em><a href="https://medium.com/the-unity-developers-handbook/goodbye-missingreferenceexceptions-hello-automated-validation-in-unity-38bbb2fc7a1a"><em>automatically validating your game to prevent broken builds</em></a><em>? Check out my other articles!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c6c421e5785" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-unity-developers-handbook/dont-re-invent-finite-state-machines-how-to-repurpose-unity-s-animator-7c6c421e5785">Don’t Re-invent Finite State Machines: How to Repurpose Unity’s Animator</a> was originally published in <a href="https://medium.com/the-unity-developers-handbook">The Unity Developer’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Clock’s Ticking: How to Optimize Compile Time in Unity]]></title>
            <link>https://medium.com/the-unity-developers-handbook/the-clocks-ticking-how-to-optimize-compile-time-in-unity-45d1f200572b?source=rss----a8b9bd588157---4</link>
            <guid isPermaLink="false">https://medium.com/p/45d1f200572b</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[unity3d]]></category>
            <dc:creator><![CDATA[Darren Tsung]]></dc:creator>
            <pubDate>Sun, 28 May 2017 19:07:52 GMT</pubDate>
            <atom:updated>2017-06-15T17:40:20.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39WiZWVmzlCCkXTl3A-JkQ.png" /></figure><p>Last Friday marked the release of <a href="http://unity3d.com/unity/qa/patch-releases/5.3.5p7">Unity 5.3.5p7</a>, a minor patch that passed by without notice or fanfare. In this patch, however, there is a bullet point nestled amongst the multitudes of other fixes that deserves much more attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxaxHrhR9TpQ-IYC4M57Ew.png" /></figure><p>That’s right. Optimizing your compile time is back!* After upgrading, my compile time went from approximately 17 seconds to 6.3 seconds.</p><p>*(After Unity 5.2.4 most versions have a <a href="https://issuetracker.unity3d.com/issues/scripts-in-standard-assets-folder-are-recompiled-everytime">compiler bug</a> which negates the most effective compile time optimization strategy)</p><p>But I’m not just here to describe how amazing it is to wait 10 seconds less every time you make a code change, I’m here to ask: Why aren’t more people excited to see this bug fixed? Does the thought of reduced compile times not incite joy in others?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*1CGlPR6ydv9Y-xYvzMuZkg.png" /><figcaption>Pictured: Not enough joy.</figcaption></figure><p>My only conclusion is that most people don’t realize they can optimize compile time. There’s no official documentation and relevant forum posts are out-of-date, so getting the big picture is not easy. But once you have that, reducing compile time is simple and the benefits are enormous.</p><p>So, here’s my personal strategy on battling compile time:</p><h4>1. Get the Facts</h4><p>First you need to find out how long it takes for your code to compile. For my own one-person codebase, it was hovering around 17 seconds. For larger teams, a fair estimate would be around 30 seconds. To put that in perspective, I make around 20–30 changes an hour and having to wait 30 seconds instead of 6.3 seconds would add about an extra 10 minutes of waiting around to my schedule <strong>per hour</strong>.</p><p>Imagine how much that adds up through the day. Throughout the week. Each month. Then multiply that number by the number of people on the team. And it’s not just about the wasted time: A longer compile time means you’re much more likely to get distracted and start checking your email or Facebook.</p><p>But first you need to know your compile time. And you want to always keep track of it, so you don’t check in anything that drastically increases it. Remember all the wasted time? To solve that, I’ve written an editor extension that you can download from my Github <a href="https://github.com/DarrenTsung/compile-time-tracker">here</a>.</p><h4>2. Optimize!</h4><p>Before we optimize, let me give you some background on how this all works. The moment you make a code change, Unity recompiles your code into a .dll (compiled code) called Assembly-CSharp.dll (or Assembly-UnityScript, etc. if you aren’t writing in C#).</p><p>To reduce the amount of time it takes to recompile, you can use special folders that Unity compiles into a separate .dll called Assembly-CSharp-firstpass.dll. The key part is that code in this .dll <em>won’t recompile</em> if you don’t change it. These special folders are named <strong>Plugins</strong> and <strong>Standard Assets</strong> and must exist on the top-level directory under Assets.</p><p>Things to note:</p><ul><li>Due to the order these .dlls are compiled in, code inside this firstpass.dll won’t be able to reference code outside of it.</li><li>Changing code inside the special folders will recompile both .dlls and negate any optimization gains.</li></ul><p>With that in mind, the best candidates for optimization are sections of code that aren’t dependent on other code and are unlikely to change. Third-party assets are perfect. Other parts of your codebase might make sense to optimize as well.</p><p>However, I did find a problem with simply drag-and-dropping all of my third-party assets to the Plugins folder. Some of those assets depend on their resources residing in their original imported path and break horribly when that is not the case. So to save myself time I bought <a href="https://www.assetstore.unity3d.com/en/#!/content/34012">Mad Compile Time Optimizer</a> ($15)***, because it leaves the non-code files where they are and also comes with a nice Revert feature.</p><p>*** I am not associated with Mad Compile Time Optimizer in any way.</p><h4>3. Look at Other Suspects</h4><p>Now that your third-party assets have been optimized, you should see a huge reduction in compile time. This is normally where people stop, but there are still a few places we can check for performance gains.</p><p>The [InitializeOnLoad] attribute is one such place. For those who are unfamiliar, <a href="https://docs.unity3d.com/Manual/RunningEditorCodeOnLaunch.html">InitializeOnLoad</a> is a Unity attribute that can be added to any class so that the static constructor is called on editor launch (or compilation finish). Any inefficient code there could add non-trivial amounts of time to your compile time.</p><p>After some experimentation, I’ve found that, yes, code that runs during InitializeOnLoad counts toward overall compile time.</p><p>To analyze instances of InitializeOnLoad, I logged time taken from the start to end of any static constructor with suspicious looking code. Most instances of InitializeOnLoad were harmless (0.0–0.2s), but I did come across one class that was abusing it to load and cache resources. I changed the offending piece of code to lazily cache when needed and moved on.</p><p>The last thing to check is your own code. Are there classes that aren’t being used? You probably don’t need them taking up time in your project. I haven’t figured out a good way to log compile time per class file, but as a general rule of thumb, file size is a good approximation for complexity.</p><p>A visualization is the easiest way to prioritize what files are worth taking a look at. I used <a href="http://grandperspectiv.sourceforge.net/">GrandPerspective</a> (Mac) because it can filter results by custom rules. I ended up making a filter that matches names ending with .cs and another to remove files with paths that contained ‘Plugins’ or ‘Standard Assets’.</p><p>This is what my project’s codebase looked like at the end of optimization. Note that my personal code is the only code compiling after a change!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbnXcpqBa2r9dxQgzvsCQw.png" /><figcaption>Yes, this is all code. Some of those TextMeshPro classes are massive.</figcaption></figure><p>TL;DR:</p><ul><li>Special folders are fixed in Unity 5.3.5p7</li><li>Always track your compile time (<a href="https://github.com/DarrenTsung/compile-time-tracker">Compile Time Tracker</a>)</li><li>Optimize by moving third-party assets to Assets/Plugins or Assets/Standard Assets (I recommend <a href="https://www.assetstore.unity3d.com/en/#!/content/34012">Mad Compile Time Optimizer</a>)</li><li>Don’t abuse [<a href="https://docs.unity3d.com/Manual/RunningEditorCodeOnLaunch.html">InitializeOnLoad</a>]</li></ul><p><em>Interested </em><a href="https://medium.com/the-unity-developers-handbook/goodbye-missingreferenceexceptions-hello-automated-validation-in-unity-38bbb2fc7a1a"><em>automatically validating your game to prevent broken builds</em></a><em>? Or maybe </em><a href="https://medium.com/the-unity-developers-handbook/dont-re-invent-finite-state-machines-how-to-repurpose-unity-s-animator-7c6c421e5785"><em>using the animator as a finite-state-machine</em></a><em> instead of building your own implementation? Check out my other articles!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45d1f200572b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-unity-developers-handbook/the-clocks-ticking-how-to-optimize-compile-time-in-unity-45d1f200572b">The Clock’s Ticking: How to Optimize Compile Time in Unity</a> was originally published in <a href="https://medium.com/the-unity-developers-handbook">The Unity Developer’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>