website_badges_steamwishlistAlpha Accesswebsite_badges_steamwishlist

Multiple character sprites using one animation controller

Update 2015.02.26
So, this post is actually a terrible way to go about this. When I was going down this path, I wasn’t aware of the built-in ways to handle something like this. Namely, you just need to create a single character’s animator controller and animation clips to feed it. Then you can create an “Animator Override Controller” that derives from that base animator for each additional character, and simply replace all the clips with unique ones. Part of this blog is to document the journey through my first Unity project, and, well, this is one of those learning experiences.

If you have several characters that your players can choose from, but all share a similar tree of Mecanim states and animations, you can use a single animation controller for all of them. Note that part of the process requires creating layers to “sync” to the master layer, and this is a Unity Pro-only feature. Here’s a quick example of some common player states, and how the process works:


With your animation states set up, make sure that you have created animation clips for each character for each of the states. For example, for the “player_fire” state, you would have animation clips such as “character1_fire”, “character2_fire”, “character3_fire”, etc. Have your first animation clip assigned to the state above.

With the first character all set up, simply add more layers in the animation controller for each character that you have. In the other layers, make sure you have “Sync” enabled (Pro-only feature). This syncs all the states with the top master layer, so all layers share the same states. Then you can simply click a layer to edit, and for each of the states, assign a different animation clip. In this example, I’ve added 4 other characters:


The last step is in your code. You can loop through all the layers in your animator, and set all their layer weights to 0 except for the chosen character, which should be 1. Here’s an example function that does this:

void SetCharacterLayer(int characterLayer)
	Animator animator = GetComponent();
	for (int i = 0; i < animator.layerCount; i++)
		float layerWeight = (characterLayer == i) ? 1f : 0f;
		animator.SetLayerWeight(characterLayer, layerWeight);

Custom Build Tools

While it’s easy enough to use Unity’s built-in build tools, you can make more customized build commands that are specifically tailored towards your game. This allows you to perform some tasks prior to exporting the final build, such as dynamically generating data files, or dynamically building a list of scenes to include.


I have a custom class extending EditorWindow, and on that window I have some simple buttons that perform build-related tasks for me. Here are some simple examples, and I’m sure you can think of more that apply to your own game to save you some time:

Generate a dynamic, custom data file used by the game:
In my example, I will have many “maps” which are Unity scenes loaded into a main scene by LoadLevelAdditive(). I have a build tool that opens every single map, gets information about it, and saves all this data (width, height, supported game modes, etc) to a master maps.json file. That way, my game menus and logic can pull this info from the file at runtime.

Define build scenes in a Constants file, and add them to the build when generating:
This is useful if you have tons of scenes that will be loaded additively (such as my maps from above), and you don’t want to add them all to the build settings dialog manually. If you have a lot of churn during development, with maps being deleted and created continuously, this is a big time saver. I have my main build scenes defined in a Constants.cs file, and I combine this list with all my maps not in the list at build time. Here’s a quick example that doesn’t work on its own as a lot of surrounding code is missing, but gives the general idea:

//---[ Constants.cs ]--------------------------------------

// scenes to include in build (in Constants.cs)
public static string[] BuildScenes = {

//---[ build tools ]---------------------------------------

// combine all the scenes to include:
List allBuildScenes = new List();

// finally, generate the build:

Pull in information and data from external sources:
I have a data file hosted on a web server that makes it easy for myself and others to continuously contribute to it whenever we have ideas. I can pull down this file in my build process and sync it with the game’s version. That way, we can contribute to it at any time, and it will be included in the next build:

// import external data file
WWW dataFileWWW = new WWW(dataURL);
while (!dataFileWWW.isDone)
    EditorUtility.DisplayProgressBar("Importing data...", dataURL, dataFileWWW.progress);
File.WriteAllText(Application.dataPath + "/Resources/data.txt", dataFileWWW.text);

Simple and flexible scrolling behavior

One of the staples of 2D games pioneered in the old school days is seamless scrolling. More specifically, having an endless scrolling behavior that seems infinite. This is usually applied to background layers, and when you combine different layers with varying speeds, you can achieve a very nice parallax effect that sells depth on a flat screen. I’ll be honest – I’m a sucker for anything with sensible parallax. To me, the effect never gets old and instantly makes smaller worlds feel expansive.

The technique is very, very simple. Perhaps it’s one of the first effects that many beginner game programmers are introduced to. It’s also probably one of the most satisfying results you’ll get in a very short amount of time.

In essence, if you create 2 copies of your scrolling layer and place them side by side, you can have them both scrolling in the intended direction, and when one of them is completely off screen, simply move it to the opposite edge. You can see the illusion illustrated here. If you pay attention to the center camera and the two hills, you can see that they appear to be seamless.


In Unity, it’s simple enough to create a small behavior script that gives the game object a speed to be scrolling at, and to snap back to the other side when off screen. If you apply this script to two identical side-by-side game objects, you can get this seamless behavior. The nice thing about the approach in Unity is that you just need to translate the objects in your Update() method, but you don’t need the offscreen-check performed every update. You can use the MonoBehaviour callback OnBecameInvisible() to handle this:

using UnityEngine;
using System.Collections;

public class Scrolling : MonoBehaviour
	public float xSpeed;
	public float ySpeed;

	void Update()
		transform.Translate(new Vector3(xSpeed, ySpeed, 0f));

	void OnBecameInvisible()
		Vector3 newPosition = transform.localPosition;
		Vector3 viewportPoint = Camera.main.WorldToViewportPoint(transform.position);
		// move to opposite edge of screen (horizontally)
		if (xSpeed != 0 && (viewportPoint.x < 0f || viewportPoint.x > 1f))
			newPosition.x = -transform.localPosition.x;

		// move to opposite edge of screen (vertically)
		if (ySpeed != 0 && (viewportPoint.y < 0f || viewportPoint.y > 1f))
			newPosition.y = -transform.localPosition.y;

		// move to the new position
		transform.localPosition = newPosition;

Give life to explosions and debris

Update 2014.08.22
I did figure out a much better approach. Read the update here!

Update: 2014.07.22
So… my hunch “this is probably too expensive in the end” turned out to be true. I’ve optimized it a little, but this is too expensive to apply to large numbers of game objects (but perfectly fine for just a few). I’ll figure out a more efficient approach for the same effect since I’ll require a lot of debris, and include the new method in a future post.


I love debris. Physical particle debris is one of the things that, in my opinion, brings modern low-res games to life. It’s also a technique that simply wasn’t feasible in the 8- and 16-bit eras due to hardware limitations. This is another reason why I would wholeheartedly argue that low-res is not simply “retro,” but a legitimate, timeless aesthetic style all its own. It is familiar yet evolving. I digress!

There are two limitations in Unity 4.3+ that I’ve had to work around to get the effect that I wanted.

The first is that the built in shuriken particle system does not support 2D physics. This means that I must use individual game objects for my debris if I want them to physically interact with the rest of my 2D colliders. So far, this hasn’t been a performance issue as I am keeping my debris in a shared object pool – a topic for a future post.

The second issue is that Unity won’t let you specify gravity in the z-direction; it’s strictly limited to x and y for 2D. My project is top-down, so to get gravity effects along the z-axis, I’m forced to use old school visual tricks to sell it. One such technique is growing sprites as they are closer to you and shrinking as they move away, and also moving them along parabolic arcs in the y direction (while adding this to their “real” y-position).

Going back to my introduction, debris should feel “alive” and dynamic, and in my case I wanted each particle to collide with the environment, and to slightly bounce until they came to rest. You can see in this example that the bounce is quite subtle, but it serves to “ground” everything and when you see it without the bounce, you’ll realize just how much it adds. I’ve always loved this sort of attention to detail in my favorite games, and they really add polish and “glue” to otherwise static objects.

For the bouncing itself, I’m running some simple tweens (using the excellent GoKit tweening library) in the y direction on each particle. The rest of their motion path all comes from a physical force I apply when they are spawned. I created a simple vertical bounce behavior script that I can attach to game objects to simulate this effect, and you can see a version of the script here. This script actually has some issues and will most likely change dramatically before the game is done, but the general idea will be the same. In fact, this is probably too expensive in the end, but so far my performance is still good:

using UnityEngine;
using System.Collections;

public class VerticalBounce : MonoBehaviour
    public float minAmplitude = 0.25f;
    public float maxAmplitude = 0.5f;
    public float minBounceTime = 0.25f;
    public float maxBounceTime = 0.5f;
    public int numberOfBounces = 2;
    public float bounceChance = 0.33f;
    private float amplitude;
    private float bounceTime;
    private Vector3 currentPosition;

    private float _offset;
    public float offset
        get { return _offset; }
        set { _offset = value; }

    void OnEnable()
        // sometimes, don't bounce at all
        if (Random.value > bounceChance)

        // choose a random amplitude and time between the specified range
        amplitude = Random.Range(minAmplitude, maxAmplitude);
        bounceTime = Random.Range(minBounceTime, maxBounceTime);
        // create a tween chain that raises and lowers the offset x numberOfBounces times
        GoTweenChain bounceChain = new GoTweenChain();
        for (int i = 1; i <= numberOfBounces; i++)
            _offset = 0f;
            GoTween riseTween = new GoTween(this, bounceTime, new GoTweenConfig()
                .floatProp("offset", amplitude, false)
            GoTween fallTween = new GoTween(this, bounceTime, new GoTweenConfig()
                .floatProp("offset", -amplitude, false)

            // each bounce should have a lower amplitude and take less time
            amplitude /= 2;
            bounceTime /= 2;
        bounceChain.setOnCompleteHandler((x) => {
            _offset = 0f;

    void FixedUpdate()
        // add the fake vertical bounce on top of the current y position (additive)
        currentPosition = gameObject.transform.localPosition;
        gameObject.transform.localPosition = new Vector3(currentPosition.x, (currentPosition.y + _offset), currentPosition.z);

Screen effects and shaders

I knew that I wanted to implement a variety of fullscreen and object shader effects to pull off some of the visuals for this project, so one of my first asset store purchases was the unbelievably full-featured Shader Forge shader editor by Joachim Holmér. At $80, it’s a steal if you’re doing any creative shader work and are looking for a good visual editor. The good thing is that it spits out shader code directly, so you can always go in and optimize/tweak the resulting shaders.

Bird's eye view of my screen effects shader in Shader Forge

Shader Forge lets you create complicated graphs quite easily and intuitively. Here’s a bird’s eye view of my screen effects shader in Shader Forge.

One of the neat things is that it provides a Scene Color node that will give you the pixels behind the object. That lets me apply this shader to a rectangle quad over only the portion of the game screen that I want to affect. Since I plan to have some UI around my central game screen, this lets me perform visual effects to the pixels “behind” this quad without affecting the rest of the UI/screen. When I am not doing anything crazy, the pixels come through unaffected as if the quad was not there, showing an unaltered game area. Note: this is one of the very few things in Shader Forge that requires Unity Pro, as the only way it can accomplish this is using a render texture.

An example of chromatic aberration in Shader Forge

An example of chromatic aberration in Shader Forge

One of the effects I wanted to implement was chromatic aberration, or color-shifting, over this gameplay area. I’m still somewhat new to shader editing, though I did a little bit of work on it for Hawken while at Adhesive. Shader Forge made it pretty easy to experiment though, and eventually I had it figured out. There is probably a more optimal way to do this, but this works and is easy to modify later when I want to improve it.


This is another example of a simple effect that was pretty easy to achieve in the shader editor. I wanted sort of a threshold-highlighting sheen effect, where objects would highlight to a key color based on a brightness threshold that is set (and can be animated). Here’s an example of the effect, and the corresponding shader.

Threshold-highlighting shader

Threshold-highlighting shader

©2019 Sombr Studio LLC