Unity: Enable the rendering Depth Buffer(URP)

Want to create a visual effect using the depth buffer but didn't get it to work? This is reintroduction on how to enable it in Unity3D when using the Universal Rendering Pipeline.
Published Sunday, 03 October 2021

Quite a while ago, when I started out writing custom shaders for Unity's build-in Physics based renderer, I wrote an article on how to enable to Depth Buffer. I have since them switched over to Unity's Universal Render Pipeline so a refresher in how to enable the depth buffer might be needed, as its disabled by default.

What is the depth buffer?

In modern game development, a renderer sometimes uses a depth buffer (also called a Z-buffer) to store the distance from the camera a certain pixel was rendered. This buffer can be very useful to have when creating custom shader effect for Unity.

Enable the depth buffer in the URP asset.

In Unity's scriptable Render pipelines (URP and HDRP as well as custom implementation), the render pipeline is saved as an asset in your project.

The first step is to find the Pipeline asset used.

In Unity, open Edit -> Project Settings. Select the Graphics options.

The first line will show the Scriptable Render Pipeline

Unity coding tips: Linq expressions

New to Unity with limited C# experience? Learn how to take advantage of what C# has to offer and improve your code by using the System.Linq namespaces.
Published Wednesday, 12 May 2021

This post is a continuation of a series in which I try to address the issue with people new to Unity who don't get to know C# and .NET good enough. In the last post I went over higher order functions and method delegates. In this post I will look into parts of the .NET library and methods that will help you write cleaner code.

Learn how to use Linq Expressions

Linq expressions (not to be confused with the Linq language also included in C# and a precursor to the Linq extension methods) are a collection of higher order function made to help you operate on collections found in the System.Linq namespace.

If you're operating on any sort of collection and wants to do any kind of operations on them, Linq can help you make the code neater and easier to read. Most of the boilerplate for iterating over lists and applying transformations are removed to a concise expression with only the transformation written out.

Example to find players who are alive


Shader effect: Invisibility shader

This post will go over how grab passes and UV manipulation can be used to create a shader effect so simulate partial invisibility.
Published Wednesday, 05 May 2021

Found myself in need of a shader in CG/Shaderlabs to visually represent units becoming invisible. They must be mostly invisible but still have cues present for the keen eye to look for.

Shader template

We'll start with creating a new Surface shader and naming it Invisibility.shader. I have made many posts before on shaders that covers the basis so for this post we will start with most stuff already setup.

The basis for the shader is a surface shader with a GrabPass. This will get the current backbuffer. We will sample it based on world space uv cordinates and end up with a practically invisible unit. This will good as a start. Then we need to make the effect more visible so we can see the unit, or hints of it, better.

Base shader codeShader "MageQuest/Invisibility" {    Properties    {    }    SubShader    {       Tags {          "RenderType"

Shader effect: Light circle

This article goes over how a selection effect circle is built for Unity using CG and ShaderLabs.
Published Monday, 26 April 2021

This post aims to create a simple visual effect for Unity to use in my character selection screen for a game I'm working on. It will be a lit up cylinder with some swirly textures on it, surrounding the character.

A visual effect need three parts.

A nice mesh.

A good shader.

Good textures.

Creating the mesh

I modeled (if you can even call it that) this cylinder in Blender. Its a simple cylinder without a top or bottom. The poly count might be a bit high but it hardly matters. It's also unwrapped to loop perfectly around from top to bottom and side to side.

That's it. Model done! Let's import it in Unity so we can start with the effect.

Writing a new Shader

I'm an old fashioned guy when it comes to shaders. I prefer to write them in CG instead if using any of the new fancy node based editors.

The shader code will be written intertwined with adding textures as we go.

Start by creating

Unity coding tips: higher order functions

New to Unity or C#? Learn some tricks to make you a better developer and write better code.
Published Monday, 26 April 2021

I have a confession to make. I kind of dislike Unity developer who has never used C# for anything else. Unity instructs you to use C# in a narrow way and there are tons of C# things they will never learn. C# has the full support of the .NET framework (technically the open source port Mono) Unity developers don't learn about. So here I am, going over a few C# tricks I think all develoeprs should know.

Higher order functions and delegates

This might sound like a very weird concept but in reality its a nice name for methods taking other methods as parameters. In older C# code you would have to look for the delegate implementation but modern C# has two classes to help you with higher order function: Action and Func. Action is used when a method don't return anything (void) and func is used whenever the method is expected to have a return value.

So the question now is how we can use them.

Simple Func example

Lets assume we have a list of Users we want to filter

Dev blog: Implementing AI states

Time to use the Behavior Graph framework to build some usable AI.
Published Tuesday, 30 March 2021
Building upon what I have

In the last post I wrote some of the theory behind the framework for this behavior graph system. Now it's time to build upon that and make something that works. This post wont be exhaustive but instead I will take a few of my implementations a show how they we're built.

Currently the framework consists of nodes, that can be either

A state, a node that makes a character do somethingA condition, a split node to determine what the next state will be based on some stateA trigger, a way to initialize (trigger) a transition between states.

Building a Idle State Node

The most basic of all possible nodes: An idle node! This node wont do anything and don't have an explicit exit transition, so triggers must be used to transition out of it.

namespace MageQuest.AI.BehaviourGraph2 {    [CreateNodeMenu("State/General/Idle")]    public class IdleState: StateBase    {        protected

Dev blog: A framework for an AI system

Revamped AI behavior graph system for MageQuest. In this post a basic Framework is designed and implemented.
Published Monday, 01 March 2021

MageQuest needs a visual AI tool that's easy to read, work with, expand upon can be serialized and handled in Git. Time to get working!

Basic idea

The AI system will be a behavior graph system, easily visualized as a nodes in a graph with edges as flows between the states. The first step is to create the node system. I don't want to spend lots of time building the graphs so I'll start with a fork of xNode, an open source graph system for Unity.

The graphs will consist of the following components:

States: Nodes that will make the unit do something.

Conditions: Makes the unit transition in the graph based on the state of its environment and itself.

Triggers: Ways to initialize a transition between states.

Flow nodes: Just helpers nodes for readability. Includes the StartNode, a component every behavior graph requires.

To follow a nice and clean design pattern, the design of the AI system

Optimizing shader performance with texture packing

Learn how to use GIMP to pack multiple grey scale texture maps into a single image file.
Published Monday, 26 October 2020

When working with shader, there is a limit on how many texture samplers a shader can use. Every sampler is also quite expensive so there is a value in using a few as possible.

Example of a bad shader

Below is a simple Shader example that will use three different grey scale maps to create a (rather ugly) shield effect.

This is the ShaderLab code making the effect.

Shader "MageQuest/MagicForwardShield" {    Properties {       _PatternTex ("Pattern", 2D) = "white" {}       _NoiseTex("Noise", 2D) = "white" {}       _AlphaGuideTex("Alpha", 2D) = "white" {}       _Scroll("Scroll", Range(0, 10)) = 1       _BaseColor("Color (Base)", Color) = (1, 1, 1, 1)       _PatternColor("Color (Pattern)", Color) = (1, 1, 1, 1)    }    SubShader{       Tags

Create a spline tool: Part 2

Continuation on how the build a spline tool for Unity. Goes over on-the-fly generation of a mesh.
Published Sunday, 25 October 2020

The last post covered how a spline tool can be created and edited in Unity's scene view. This post covers how we can use that data and create a mesh around it to get a cable.

Full source for this and the previous post can be found at

Quick recap

We have a CableSpline.cs file containing the monobehaviour that represents and spline (and soon are cable as well) and Editor/CableSplineEditor.cs containing the editor.

We left of with an empty UpdateMesh() in the CableSpline class method. The goal is now to implement that method.

Build the mesh generation

Out cable will need some new Unity components to work. Add these two attribute above the declaration of the CableSpline class.

[RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshRenderer))] public class ConnectionSystem : MonoBehaviour 

The next time a CableSpline is created it will automatically add these two components to the

Create a spline tool: Part 1

Learn how to use cubic Bezier curve the create a spline based on control points.
Published Saturday, 03 October 2020

This post is the first part of two on how to create a spline based cable tool, based of Cubic Beezier curves, editable in the scene. In this post we will cover how to create the base scripts and an editor for it. The next post will cover how we can generate a cable mesh to surround the spline.

Full source can be found at

Create the Cable Spline

Create a new file named CableSpline.cs in your project, and empty out anything apart from the class declaration.

using System.Collections.Generic; using System.Linq; using UnityEngine; public class CableSpline : MonoBehaviour { }

The spline will consists of a series of control points along which the cable will run. Each of these points will need a relative position and a direction they are facing. Add this class as a nested class inside the CableSpline class.

[System.Serializable] public class SplineControlPoint { public Vector3 Position; public Quaternion Direction

Better tools visualization: adding editor handles

Improve the usability of Unity Editors by adding Handles. Real examples from Bonafide Prefab Painter Unity Addon.
Published Wednesday, 30 September 2020

I'm trying something different for this post. BonaFide Prefab Painter is a Unity addon created by me, available for purchase in the Asset Store. I'm working on improving its usability by adding something Unity calls Handles and the plan is to go over how that is done at the same time.

Changes mentioned will be available in the (at time of writing) next version of the prefab painter, v2.5.4.

If you're not familiar with Bonafide prefab painter (doubt anyone is), it's a prefab painter tool I made for Unity for my current game project to quickly place hundreds of prefabs in a scene with a certain degree of control and help me build levels. The game is question is a top-top co-op action game, similiar to the Diablo series, so that's the kind of maps the Editor is created with in mind.

Quick example of what it can do:

The tool supports a few different brush types that will place prefabs in different ways, for example a circle, a square and a line.


Unity editor: More tricks to protect you from yourself

Examples on how to create PropertyAttributes and PropertyDrawers to make better Unity Editors.
Published Monday, 28 September 2020

In the last post I went over a few simple and ready-available C# Attributes to make better inspectors. This article will cover how you can extend the Unity Editor and make a few attributes yourself.

Create a C# attribute from scratch

Attributes is a language construct in C# that's used to add metadata to classes, methods, and variables. They all inherits from the abstract base class Attribute. When working with Unity properties, they have their own abstract base class PropertyAttribute that you should inherit from.

In the last post I showed how [TooltipAttribute] can be used in your projects. That attribute is very simple to recreate and will serve as an example for how to create Unity property attributes with custom property drawers.

Somewhere in your Unity project, create a new

Unity editor: Tricks to protect you from yourself

Collection of tips on how to make Unity editors more useful and less error prone.
Published Tuesday, 01 September 2020

When working a lot in Unity it's easy to get crashes and errors because you forget to set the correct data in components, or having forget to add a component type altogether.

This is common and there is no silver bullet to solve it bu there are however steps you can take while writing your code to decrease the chance of making mistakes. Many of these tricks are built-in in Unity's editor from start and very simple to get started with.

Adding tool tips

Naming variables is hard. They have to convey a lot of meaning while still being short. In programming, comments are there to help you when you need more information about a variable. Unfortunately they wont be visible in the inspector.

This is where the[ToolTip("")] attribute comes in handy. Add this to any public variables in behaviors and they will be displayed when you mouse-over the field in the inspector. Write down what the variables does and any special considerations needed when setting it

Shader effect: Soft "alpha clipping"

Simple way to fix some less-than-perfect textures for visual effects using built-in shader functions for Unity3D.
Published Sunday, 03 May 2020

Short solution to a simple problem I came across. I downloaded a ready made effect from the Asset store and found a gray scale texture with no easing before the edge. I'm not sure how to describe it so a picture might be the best example.

As can be seen here, when rendered with transparency the edges of this texture are very clearly visible against the black background because the texture is drawn all the way to the edges. If used in a particle system it will look very obvious.

The best solution

If you are creating the textures yourself, the solution to this problem is to not draw all the way to the edges if the images. But that's of course not what this blog entry is about.

Fixing it in the shader

The goal is to find a way to solve the issue of softening the edges of the image in the shader instead. As mentioned above, it would be simpler and more efficient, compute power wise, to just go back and fix the source image but that is not always possible.


Unity: Enable camera Depth Buffer

Want to create a visual effect using the depth buffer but didn't get it to work? This is how to enable it in Unity3D.
Published Thursday, 09 April 2020
What is the depth buffer?

In modern game development, a renderer sometimes uses a depth buffer (also called a Z-buffer) to store the distance from the camera a certain pixel was rendered. This buffer can be very useful to have when creating custom shader effect for Unity but is unfortunately not always enabled. Luckily there are a few ways to remedy this.

Use the deferred rendering pipeline.

If you use Unity's deferred rendering pipeline the depth buffer is enabled by default because deferred rendering uses it.

You can set your game to use deferred rending by changing it from Edit->Project Settings -> Graphics. Every tier will have a Rendering Path setting from where you can select Deferred.

Enable it manually for a camera.

Create a new C# script for your game as follows and attach it you your camera.

Note: The editors camera will have it's Depth Buffer enabled if the game camera does.

using UnityEngine; [ExecuteInEditMode] [RequireComponent(typeof(Camera))] public

Unity Effects: Decal shader

Create a decal effect shader for Unity3D from scratch.
Published Wednesday, 08 April 2020
What is a decal?

Ever played a shooter where bullet holes appear as fire at a wall? Seen blood splattered or footprints across the floor? Then you've most likely seen decals. In game development a decal is a mesh with a texture rendered into a scene that takes no space of its own but is instead projected down onto the underlying geometry. In essence you are rendering stuff onto other stuff.

Example of a decal texture being projected down onto the underlying geometry.

Creating decal shaders in Unity

For some reason Unity has no decal shader available out-of-the-box which I find rather funny because I have based this article upon one written by Unity themselves back 2015 (Extending Unity 5 rendering pipeline: Command Buffers). There are probably plenty of implementation available in the Asset Store as well but they are not particularly hard to create from scratch so why pay for something when you can learn to create it yourself?

This shader relies

Unity Effects: Soft glow

Recreating a soft light glow effect found in World of warcraft in Unity3D using ShaderLabs/Cg.
Published Saturday, 04 April 2020

Full honestly from the start. I've been playing quite a bit of World of Warcraft Classic lately and it has been great opportunity for me to get inspired graphics wise. I was running around in Duskwood, a really dark and moody area of the game when I came across one of their light posts. It had a soft glow surrounding the light source making it look more present. This is an effect I want to recreate for my own game in Unity.

Creating a custom shader

This visual effect requires a custom shader. First I need to determine what results I'm going for.

Is in every sense of the way a billboard. Just a plain quad always facing the camera.Does not interact with lightning in the scene. Any actual light from the prop will be handled with Point Lights.Appear to "light up" meshes underneath it.Be non-static / change is subtle ways.

This boils down to an unlit transparent additive shader, billboarded, scaling it correctly and slowly changin it's size back and forth

Unity editors: Getting started

Get a quick quick overview of Unity's editor API, how to access it and some very early and simple pitfalls you should avoid.
Published Friday, 27 March 2020
Creating your own Unity tool from scratch

This blog post will cover the basics of how to setup your project in order to create some custom editors. What is written here applies to all custom editors wether they be Editors, Editor windows, custom property drawers, custom object previews etc.

Unity3D is can be great game engine to work with and it gets more features added all the time. The tooling for Unity is however quite lacking in many areas. Their solution to this is an extensive editor API allowing for custom tools. If you are looking for something, Unity's Assets store and are both full of tools. But what do you do when you cant find what you are looking for? The answer is easy: build your own.

Accessing Unity's Editor API.

For performance and build size reason Unity has chosen to split their API up in several different parts (called Assemblies). The Editor part of Unity is only used when working in the Unity editor and is therefor not included