Notes from the KAYAC hyper-casual team
Tag: Unity (57)

Game Programming Training
A three-day training course in which new engineers build games such as Tetris and Flappy Bird in Unity "with code only", through a minimal drawing interface: why code skills still matter in casual game development, how the training ran, and the 2D and 3D template projects published on GitHub.

Memories of Developing a Certain Sumo Game
How a sumo game built for an in-house event in about 72 hours moved its wrestlers as ragdolls driven only by AddForce() and AddTorque() with PID control, and how that idea later turned into Draw Saber.

Approximating Average FPS the Easy Way
A cheap way to approximate average FPS without an array or a loop, by shrinking the running value by a fixed ratio and adding the new frame time, plus a rough variant using powers that keeps load spikes visible.

Easy Full-Screen Anti-Aliasing to Reduce Jaggies
A comparison of the anti-aliasing options available in Unity, MSAA x2, MSAA x4 and FXAA: how they look, frame rates measured on two Android phones, how each technique works, and which one to pick for smartphones.
Writing Out Every Asset Reference
A Unity editor tool that writes out which assets reference which, and everything each prefab, scene and ScriptableObject pulls in: how to use it to check for unused assets or bloated scenes, how it is built on AssetDatabase.GetDependencies, and ideas for extending it.

On the Size of Nested Prefabs
An experiment showing that Unity appears to expand nested prefabs in full at build time, so build size and load time grow with the real number of GameObjects, plus how ParticleSystem bloated a product's stage prefabs and some ideas for countermeasures.

Interactive Content Linking a Web Browser and Unity with Firebase
A mock-up that uses a phone browser as a controller for Unity effects: touch coordinates go from the web page to Firebase Realtime Database, through a local Node.js WebSocket server, to Unity via websocket-sharp, and finally drive a VFX Graph.

Compute Shaders on Low-Priced Smartphones
A simple benchmark that runs XorShift over every texel of a texture on the CPU and with a compute shader in Unity, measured on a low-priced Android phone and on high-end devices, with an explanation of the compute shader implementation and thoughts on when moving work to the GPU pays off.

"Which Textures Are the Big Ones?" Dumping a List of Textures
A small Unity editor script that lists every texture in a project with its estimated memory size, format and settings, so you can find oversized textures and see where the size goes.
How to Change an Android Device's Resolution with ADB, and What It's Good For
Changing a connected Android device's resolution with `adb shell wm size`, and using it to check in seconds whether a game's low frame rate comes from fill (fragment shading), what to do if it does, and what to suspect if it doesn't.

Do We Even Need UnloadUnusedAssets()?
An experiment in Unity 2018.4 showing that textures are not freed automatically unless Resources.UnloadUnusedAssets() is called, in the editor and in a macOS build, with thoughts on when to call it and a pitfall with it in editor extensions.
Combining C#'s ConditionalAttribute Conditions with AND and OR
How to combine several symbols with AND or OR in C#'s Conditional attribute by wrapping it in an inverted #if with a never-defined symbol, and why this works while defining a new symbol with #define does not.

The Cost of Unity's Debug.Log and the Depth of the Call Stack
An experiment showing that the time and GC Alloc of Unity's Debug.Log grow with the depth of the call stack, and what to do about it: skipping stack traces, using a lighter log, and not nesting StartCoroutine.

I Tried Making a Confetti Effect with Physics Simulation
A confetti effect in Unity built from point-mass physics: each scrap of paper is two point masses with Verlet integration, air resistance along slightly bent normals and a quaternion for orientation, drawn in bulk with skinning-based pseudo-instancing and a small color atlas.

(For Artists) The Pitfalls of LDR Bloom, Plus a Word on HDR vs. LDR
Why a bloom effect on an LDR canvas can't tell bright highlights from merely bright colors, how drawing everything darker and scaling it back up works around this at the cost of precision, and when to simply use HDR instead.

Sending Assets Straight from the Unity Editor to a Phone for Checking
A prototype that builds the selected prefabs into an asset bundle in the Unity Editor and sends it over Wi-Fi to an HTTP server running on a phone, so artists can check them on the device right away, with notes on the motivation, connection handling, transfer speed and shader replacement.

Keeping Pixel Density Constant with Unity's Fixed DPI Resolution Setting
What Unity's Fixed DPI resolution scaling mode does, why lowering the resolution by pixel density helps frame rate and power consumption on phones, and a table of the pixel densities of common devices.

Using Skinning to Draw Lots of Objects, Instancing-Style
How to draw thousands of copies of a mesh in Unity with a single SkinnedMeshRenderer and one-bone skinning instead of GPU instancing, with performance compared against plain GameObjects and GPU instancing, and the limits on bone and vertex counts.

Getting a Mesh Out of Unity as an .obj
How to save a mesh generated in Unity as an asset with AssetDatabase.CreateAsset(), and how to write it out as an .obj file from a context menu so it can be used outside Unity, with a short look at the .obj format.

Trackball-Style Camera Control Using Quaternions
A camera you rotate by dragging a trackball-like sphere, built in Unity with quaternions: integrating angular velocity, turning drags into angular velocity with a cross product, inertia, and what quaternions are good for.

Quietly Dangerous - On the Precision of Shader Variables
How floating-point precision works and why using half for UVs and positions in a shader causes bugs that appear only at high resolutions and only on some devices, with a few related pitfalls.

I Want to See Sound Spectrum Analysis on an Actual Smartphone
A small Unity component that shows a spectrum analysis of the output sound on the device, used to see how much compression cuts the high frequencies, with how to use it and how it is implemented.

Height-Dependent Fog - Getting That "Gas Pooling in the Low Ground" Look
Building a fog that thins out with height in a Unity shader: from basic exponential fog, through a fog that ends at a fixed height, to a fog whose density falls off exponentially with height, derived by integration.

Applying Filters to Sound in Unity
An introduction to the audio filters Unity provides (chorus, distortion, echo, reverb, low-pass and high-pass), why changing sounds at run time to match the game's situation is worth it, where each filter might be used, and whether to put filters on an AudioSource or the AudioListener.

I Love the Log-Normal Distribution
An easygoing introduction to the log-normal distribution: how it differs from the uniform and normal distributions, how to generate it in code, where it shows up in money and society, and how it can be used in games, from random tap tests to dummy user data and damage design.

Automatically Testing Unity Apps with Indiscriminate Tapping
A tool that makes several virtual pointers tap, drag and long-press all over a Unity app through EventSystem for endurance testing: how to use and customize it, how to run it overnight, and the pitfalls of reproducing EventSystem's behavior.

I Want to Fit Things on Screen Just Right in a 3D Game! Automatically!
How to compute a camera position, with direction and field of view fixed, so that a set of points in 3D space just fits on screen, worked out first in 2D and then turned into Unity code.

"For Now" Rendering Settings for 3D Smartphone Games
A rough guide to lighting calculation (direct, indirect and environmental light; diffuse and specular reflection) and the default lightmap, shadow, LightProbe and quality settings I use when prototyping 3D smartphone games in Unity, with measurements on a low-end phone.

Rotating a Vector in 3D Space
How to scatter beams in a cone around an axis in Unity: with a Transform, by converting a local vector to world space, and without one, by building a RotateVector function from projection, dot and cross products.

I Want to Scatter Points Randomly on a Circle or a Sphere - Building Distribution Functions with High School Math
How to scatter points uniformly on a disk, a sphere and a hemisphere, and how to bias them toward the pole with a tunable parameter, by building a cumulative distribution function with high school calculus and inverting it.

Homing Calculations for Beams and Missiles
How the beams in a particle demo home in on their target: the common ways to steer toward an enemy, and the method used here, which bends the velocity with a capped centripetal acceleration and keeps the speed constant with propulsion and damping.

In Praise of Decibels
Why sound professionals use decibels rather than Unity's 0-to-1 volume values, how to convert between the two, why everything people see should be in decibels, and a trick for making volume sliders easier to use.

A Debug HTTP Server on Smartphones (2): Browsing the File Tree and Editing in Place
The second part of running a debug HTTP server inside a Unity app on a phone: browsing the StreamingAssets file tree and editing text files in the browser, with notes on generating HTML with XmlWriter, the trailing slash, listing StreamingAssets on Android, and storing a tree with JsonUtility.

Making My Debug UI Independent of UGUI with a Homemade Raycaster
How I wrote my own Raycaster so my debug UI library no longer needs a Canvas, along with the other improvements to the library: MeshRenderer drawing, alignment, nested menus, graphs, text sizing and safe area support.
Running a Debug HTTP Server on an Actual Smartphone
Running an HTTP server inside a Unity app on a smartphone so a PC browser can upload files and swap assets on the device directly, with the implementation and the open problems for using it in production.
Dynamic Waveform Generation That Plays Sound Without an AudioClip
Generating audio waveforms at runtime in Unity with MonoBehaviour.OnAudioFilterRead: a piano-like toy that sums 88 spring-damper oscillators, how to set their stiffness from each key's frequency and their pulse from the desired amplitude, and ideas for taking it further.

Changing the Perspective of CG with Shaders
A Unity post-process shader that turns ordinary perspective rendering into a fisheye-like azimuthal equidistant projection, so wide fields of view don't stretch the edges, with a vertex-shader speed-up and the problems that remain before it could ship.

Bloom Effects Even on Cheap GLES2 Phones
A post-process bloom effect for Unity that runs within GLES2 on low-end phones, based on Kawase's multi-resolution Gaussian blur: how it works, how it cuts render target switches, draw calls and texture reads, its quality limits with 8-bit buffers, and how its GPU load was measured.

The Traps Lurking in C# structs
The traps I fell into using structs in C# (mostly in Unity): copies on return and assignment, Vector3.Set() and properties, structs in arrays, and the boxing that makes Dictionary and sorting allocate, with the rules I drew from them.

I Made a Library That Eases Some of My Gripes with AssetBundles
A sample Unity library that downloads AssetBundles, stores them locally and loads assets from them: its features, how to use it, how it manages local files and dependencies, why it is asynchronous only, and its debug features.
Keeping Assets from Being Duplicated Between AssetBundles and the App Itself
A Unity editor tool that lists references from assets outside a chosen folder to assets inside it, to catch AssetBundle material that the app's own prefabs still reference, with how it works, ideas for customizing it and related dependency searches.
When to Use a Linked List (LinkedList)
A concrete case where arrays and dictionaries are not enough: a download queue that must keep insertion order and allow canceling from the middle, solved with a dictionary plus a linked list, then made allocation-free as an intrusive linked list, with a rundown of the data structures I keep in my toolbox.

Which DownloadHandler Is Fastest for Downloading and Saving AssetBundles?
Measurements of downloading and saving 1,000 AssetBundles in Unity with DownloadHandlerAssetBundle, DownloadHandlerFile, DownloadHandlerBuffer with synchronous saving, and a custom DownloadHandler with asynchronous saving, looking at parallelism, randomized order, time, memory and spikes, with the implementations explained.

What I Wondered About When I Wanted to Use Random Numbers from Threads in Unity
A comparison of random number generators that can be used from threads in Unity (System.Random, MWC, XorShift, and the XorShift128 said to be inside UnityEngine.Random): their speed, their randomness as images and in the gorilla test, and their memory use.

Making Unity Debugging More Efficient with Slack
How Tokyo Prison posted screenshots, textures, logs and device information from Unity to Slack to support debugging, with sample code for each kind of post and notes on how we ran it in practice.

Texture Compression with Luminance + Chrominance (YUV, or YCbCr)
A texture compression technique for Unity that converts RGB into luminance and chrominance and halves the resolution of the chrominance, with the encoder, the decoding shader, results, weaknesses, alpha support, and a comparison with indexed color.

Rethinking 16-Bit Color
How reducing textures to 16-bit color (ARGB4444 and RGB565) works, how to round so the error stays small, why banding shows, and a custom Unity importer that applies Floyd-Steinberg dithering.

Visualizing Compile Time in Unity
An editor extension that shows how long Unity's script compilation takes, a look at what makes compilation slow (mostly the sheer amount of code), and a tool for measuring how much code each folder of a project holds.

I Made a WebGL App That Measures Device Performance
A rough benchmark built with Unity WebGL that measures CPU and GPU performance on PCs and smartphones, with results across devices and what each test reveals about the hardware behind it.

Making Multi-Resolution SafeArea Support in Unity Less Painful
A component that scales and anchors each RectTransform for any resolution, aspect ratio and SafeArea, based on what was done for Tokyo Prison: how to use it, why it was designed this way, and what still needs testing on devices.

Animation Made with Interpolation Functions
The basics of making animation in code: linear, quadratic and cubic interpolation, exponential interpolation computed step by step, and a spring-damper, with how each one moves and how to keep it from blowing up.

Making Effects That Travel Between the 2D and 3D Worlds in Unity
How to send effects between characters in a 3D world and 2D UI drawn by a separate camera in Unity: placing 3D effects at a UI element's position, and drawing 2D effects that look as if they move in 3D, with the vector math.

(Semi-)Automatically Converting What You Made in After Effects for Unity
A tool that converts animations made in After Effects into C# code and GameObjects for Unity: why convert rather than rebuild by hand, the workflow, how the converter and runtime are built, and the problems still left (SpriteRenderer support and draw order).

Memories of Indexed-Color Textures: The Good Old Palette
An experiment implementing indexed-color (palette) textures in Unity: their pros and cons against ETC2 and other formats, the importer, component and shaders (including hand-written bilinear filtering), speed measurements, and palette animation.

I Can't Stand UnityEngine.UI.Image Painting the Transparent Parts
A UnityEngine.UI component that draws a sprite using the sprite's own vertices, or hand-edited ones, to cut the area painted compared with the standard Image, step by step through size, pivot, atlas packing, vertex editing and gizmos.

A Performance Investigation of UnityEngine.UI That Began with "Doesn't Rich Text Add a Crazy Number of Vertices?"
Why rich text tags and Outline inflate vertex counts in UnityEngine.UI, a component that strips the empty quads, and measurements of which UI operations (Text.text, Graphic.color, sizeDelta, moving, rotating, scaling) are actually slow.

[Unity] A Debug UI That Leaves the Scene Clean and Draws in a Single DrawCall
Why neither UnityEngine.UI nor OnGUI suited my debug UI, and how my own library builds windows from code alone, draws everything with one Mesh in a single DrawCall, and takes input, with a frame time gauge as an example control.