Creating 2D Games With Unity3D Part 2

Project IconThis is part 2 of a multi-part series on making 2D games with Unity3D. Part 1 covered the basic tools you’ll need, some basic concepts, and initial camera and scene setup. Part 2 focuses mostly on the Sprite Manager 2 workflow including some tips and tricks. I should probably mention that I’m not affiliated with A and B Soft (makers of Sprite Manager 2), SM2 just happens to be the best tool I know of for working with sprites in Unity3D. That said, the remainder of this series will focus heavily on SM2 so you may want to get it if you’re not already using it.

If you haven’t already watched the SM2 tutorials on the A and B Soft website yet, you should check them out. SM2 seems a little tricky at first, but once you get the hang of it it’s easy to use and a huge time saver. Also I should mention that I’m using Sprite Manager 2 version 1.8 and Unity 3D version 3.1.

Installing Sprite Manager 2

SM2 comes bundled as a .unitypackage file. There are 2 ways to add these into your project, I’ll go over both methods. First create a new project in Unity (File -> New Project) or if you’re adding SM2 to a project you’ve already started, that’s cool too (and likely a common scenario).

Method 1) In Unity go to Assets -> Import Package and then browse to the location of the SM2 1.8.unitypackage (note you may be using a different version, that’s totally fine). Select the SM2 1.8.unitypackage and then click the Open button.

Method 2) Browse to the location of the SM2 1.8.unitypackage on your hard drive and double-click the file to open it – the package should automatically open in Unity.

When using either of the two methods described above, the “Importing package” window will appear in Unity which lists all of the files in the package. On the Importing package screen, make sure all of the little boxes on the left are checked (which they should be by default) and then click the “Import” button in the lower right hand corner of the window. Assuming you’re starting from a clean project, you should now have the following folders in your Project view: Editor, Materials, Plugins and Shaders. Some of those have subfolders as well and all of them contain SM2 related files. Check out this image to see what your Project folder should look like (again, assuming there wasn’t anything else already in your project).

Upgrading Sprite Manager 2

SM2 is regularly updated by the author to fix bugs and add new features. When upgrading to a new version of SM2, it’s best to delete all of the previous version’s files from your Project before installing the updated package. Be careful with this – make sure you’re not deleting files that aren’t related to SM2 or any SM2 files that you may have modified (you might have changed attributes on the Sprite Material or the Shaders for example). Also make sure you don’t just delete the entire Editor or Plugins folder if you’ve imported other scripts or plugins into your Project that live in those folders. Refer to this image to see exactly what was added when you installed SM2 and only remove only those files before upgrading. It’s certainly not an ideal workflow, but it should go smoothly if you’re careful.

Creating Textures

I save all of my textures as .png files from Photoshop into a folder named Sprites in my Unity project’s Asset folder (eg Assets/Sprites). After saving the file, switch to Unity and find it in the Project panel in the Sprites folder (assuming that’s where you saved it). Now you’re going to need to make some changes to the Texture Import settings:

Select the texture in Unity, then in the Inspector under Texture Importer set the following:

  • Texture Type: Advanced
  • Non Power of 2: None
  • Generate Mip Maps: uncheck (since you’re probably not going to be moving the camera in/out in your 2D game, this will keep the file size smaller)
  • Override for iPhone: leave this unchecked.

Click Apply. Now if you look at the Preview window in the Inspector (with your sprite still selected), you should see information like “24×24 (NPOT) ARGB 32 bit 2.2 KB”. SM2 requires textures to be either ARGB32, RGB24 or Alpha8. If you use the “Override for iPhone” option and set it to something like “RGBA 32 bit”, you’ll get errors when you Build Atlases. If you did happen to use those override settings, just uncheck the Override box, click Apply and you should see the file is set back to ARGB 32 bit.

If you have a lot of textures, changing the attributes on each one (as described above) can be a tedious process. Thankfully there’s an awesome script on the unifiycommuntiy Wiki that provides a way to change the import settings on several textures at once. Follow the instructions on the wiki page to add the script to your project. Once you have the script, do the following:

  1. Select 1 or more textures in the Project view
  2. Custom -> Texture -> Change Non Power of 2 -> None
  3. Once those settings are applied, the textures will automatically deselect. Select them again in the Project view
  4. Custom -> Change MipMap -> Disable MipMap

Creating A Sprite With SM2

Here are the steps I use to create a new sprite:

  1. GameObject -> Create Empty
  2. zero out the x,y,z Position (not required, but helpful)
  3. Component -> Scripts -> Packed Sprite (this will add SM2′s Packed Sprite script to the GameObject)
  4. Window -> Sprite Timeline (opens SM2′s Sprite Timeline window)
  5. With the empty game object still selected, drag the texture (with the settings from above) into the Static Texture field in the Sprite Timeline window.
  6. Drag & Drop the Sprite Material from the Materials folder onto the object or into the inspector window (if it’s still selected)
  7. Check “Pixel Perfect” and “Auto Resize” under Packed Sprite on the object
  8. Custom -> Build Atlases (I typically use the default settings)
  9. Press Play to see the sprite appear properly sized. Note if you had the Sprite Timeline open in front of the game view when you press Play, the sprite might appear smaller than it should in the Game view. Make sure the Game panel is on top and press Play again to see it properly.

If you’re making an animated sprite, add these steps between Step 5 and 6 above:

5a. In the Spite Timeline editor, click +, and give it a Name (eg. walkright) which can later be referenced in script.
5b. Drag your animation frame(s) from your Sprites folder into the light gray bar under the Static Texture area. You can drag them one at a time or many at once.
5c. Set the FPS to whatever is appropriate for your animation (eg 24),
5d. If you intend your animation to loop, then put -1 in the Loop Cycles field.

Sprite Atlases

The first time you Build Atlases, a new folder will be automatically created in your Project named “Sprite Atlases” and a new Texture will be created in the folder called “Sprite Material”. The name of the Atlas is based on the Material name – so if you had assigned a Material called “Sprite Material Player” to your Packed Sprite in Step #6 above, then there would be a new Texture in that folder called “Sprite Material Player”.

You can have as many sprite materials and corresponding sprite atlases as you want – for example you can have a material/atlas for the player, for the user interface and for the backgrounds. But keep in mind that each Atlas = 1 additional draw call so it’s best to try to fit all of your textures onto as few Atlases as possible to keep draw calls low. However you need to balance draw calls vs. texture size – the more textures you assign to an Altas, the larger it will get. A 1024×1024 Sprite Atlas might be 2MB or more. If you’re trying to keep your app size down and have some draw calls to spare, then you could distribute textures onto another Atlas so that you end up with 2 smaller Atlases which may end up taking up less disk space (your milage may vary).

You should also make sure that your newly created Sprite Atlas isn’t compressed as nothing will make your 2D game look worse than compressed textures (again, your milage may vary depending on your projects needs).

  1. In the Project panel, select the Sprite Material that’s in the Sprite Atlases folder (not the one in the Materials folder)
  2. Override for iPhone: Checked
  3. Format: Truecolor (note the options here may be different for different platforms, just make sure it’s not set to “compressed”).

Playing The Animation In Script

Here’s a simple javascript example of how you’d play that animation:

var characterSprite : PackedSprite;

function Update() {
if(Input.GetMouseButtonDown(0)) {
     WalkRight();
}

function WalkRight() {
     characterSprite.PlayAnim(0);
}

Update: One of our readers wanted to know how to make the character walk right/left and play corresponding walk right/left animations. Here’s a simple C# script which will move the player left or right when you press the left or right arrow keys and will also play the left or right walking animations (you’ll need your own walking animations) on the player.

  1. Create a new script and name it Controls.cs
  2. Copy the script below and paste it into Controls.cs
  3. Follow the steps above section titled “Creating A Sprite With SM2″
  4. Drag the Controls.cs script on to your player sprite game object
  5. Assign the playerSprite to the script by dragging it onto the playerSprite field into the inspector.
public class Controls : MonoBehaviour {
	
	public PackedSprite playerSprite; // assign your sprite to this in Unity
	public float moveSpeed = 2f;
	private float movement;

	void Update() {
		movement = Input.GetAxis("Horizontal") * moveSpeed;
		movement *= Time.deltaTime;
		transform.Translate(movement,0.0f, 0.0f); // move player along X axis
		
		// move right
		if(movement > 0.02f) {
			playerSprite.PlayAnim(0);
		}
		
		// move left
		if(movement < -0.02f) {
			playerSprite.PlayAnim(1);
		}
	}
}

In part 3 of this series, I'll go into more detail on playing different animations on a character.

Creating Prefabs

Once you've created a new sprite and built the atlases at least once, you should make a prefab out of it. The reason you want to have your sprite objects in prefabs is important if you have a game that has multiple Scenes each with SM2 sprites in them - the sprite builder can't talk to sprites in other scenes so when you rebuild atlases in one scene, you can destroy the sprite mappings on object in other scenes. But if all of your objects containing sprites are on prefabs, then they will be updated when you Build Atlases (I think the Scan Project Folder box needs to be checked in order to update prefabs).

  1. In the Project view, create a new folder and name it Prefabs
  2. Change the name of the prefab (eg. Player)
  3. Drag the Player gameobject from the Hierarchy view onto the Player prefab in the Project view. You'll know it worked if the object in the Hierarchy view turns blue and the little cube icon on the prefab turns blue too.

Note that any time you make changes to your prefab (like if you add a script or add components or add more sprite animations), in most cases you'll "break the prefab reference". Don't worry about that, just make your changes and when you're done drag the object onto the prefab again as described in Step 3. Sometimes your changes won't break the connection, but you'll still want to update the prefab - to do this select the object in the Hierarchy, go to Game Object -> Apply Changes to Prefabs.

Thoughts On File Size

Using Sprite Manager *should* actually keep your file sizes smaller than they would be if you just built the scene out of individual textures since each texture is being added to a single Sprite Atlas and extra empty space is being trimmed between them. Your individual textures in your Sprites folder actually aren't even part of the build once they're assigned to the Sprite Material's sprite atlas. But the best reason to use SM2 is that all of the sprites on a single spriteatlas will = just 1 draw call in the engine rather than a draw call for each individual texture if you placed them in the scene individually (this is especially important on mobile devices).

Conclusion

That's all for part 2 of the series. As always, my aim is to make these posts as useful as possible so please use the comments area below if you spot any errors, have questions or suggestions for future posts or if you just want to say "hi". In the next installment I'm planning to go through the process of creating a simple 2D platformer game.

More Tutorials In This Series

Creating 2D Games with Unity3D Part 1
Creating 2D Games with Unity3D Part 2
Creating 2D Games with Unity3D Part 3
Creating 2D Games with Unity3D Part 4
Creating 2D Games with Unity3D Part 5

And here's another more recent tutorial series that uses Orthello (free) for the sprite display and animation duties:
Make A 2D Game in Unity3D Using Only Free Tools Part 1
Make A 2D Game in Unity3D Using Only Free Tools Part 2
Make A 2D Game With Unity3D Using Only Free Tools Part 3
Make A 2D Game With Unity3D Using Only Free Tools Part 4
Make A 2D Game With Unity3D Using Only Free Tools: Beginning Enemy AI With A* Pathfinding

Resources

Texture Import Settings script
Unifycommunity Wiki

Show Your Support

If you find these tutorials useful, please considering buying one or more of our games and apps for iPhone and iPad. Your support helps to keep the tutorials flowing!

  • Giant Moto: High flying arcade style motocross action!
  • Small Space: Fly a spaceship, eat space creatures, score point!
  • Holeshot Drag Racing: High speed drag racing action!
  • Alien Booth: Transform pictures of your friends into awesome aliens!
  • iSpoof Walken: A hilarious look into the world of Christopher Walken!
  • Gaga Eyes: Transform pictures of your friends to give them huge anime eyes!

About the author

Tim MillerTim Miller is a veteran game developer with over 15 years experience in the video game industry working as a Level Designer and Lead Level Designer at LucasArts, Secret Level and Nihilistic Software. He co-founded Rocket 5 Studios with his wife Cathy and their dog Rocket in 2009. Twitter, LinkedIn, Portfolio

Share/Bookmark
  • http://twitter.com/pitaman Carlos Pita

    Amazing. Again. ;0)

  • Pingback: New post format / 5 more hours per day could help… « GFX47's Blog

  • http://twitter.com/solidd_swa solidd_swa

    oh cool :) so far so good.

    but how can i apply collisions to this sprite now?

  • http://www.rocket5studios.com/ Tim Miller

    There are a few different methods for adding collision to sprites, and I plan to cover that topic in detail later in the series.

    The simple way is to use a Unity GameObject like a cube, sphere or capsule for sprite collision. Create an object, scale it so it’s about the right size for the sprite and then make the sprite a child of the object.

    If you need accurate collision, then you could bring your sprite texture into a 3D app like Maya, build polygon collision that matches the shape of your sprite, import the model into Unity, and then make the sprite a child of that collision object (you may need to apply some settings on the object to make it work as collision, depending on your 3d package – see the Unity docs).

  • http://twitter.com/solidd_swa solidd_swa

    i look forward to your tutorials…. my first game will be a result of your tutorials by the way, so the faster you release them the faster i will finish my game ha ha

  • Thomas Troelsen

    Great tutorials! Thanks for the effort – I am looking forward to the next one .-) Just a few small notes to Tutorial 2 (for n00bs like myself): I was not able to locate the mentioned “Scan Project Folder” checkbox, and you just missed the Assets -> Create -> Prefab step.

    Keep it up!

  • http://www.rocket5studios.com/ Tim Miller

    Thanks for the feedback, Thomas. The “Scan Project Folder” option should be in the Build Atlases window (Custom -> Build Atlases). If you don’t see that option, you’re probably using and older version of Sprite Manager 2.

  • GameAreGood

    I just read this one and I like it. Good suggestion about making sure the final Sprite Material isn’t being compressed. Looking forward to what you cover in future posts!

  • Berkeleyoc

    Hi, I am having some problem with the scripting. I am new to this and I have tried to create a new JS and paste the code you put but it does not really work. AM I supposed to create a new JS and attach it to the Game Object or modify the Packetsprite script that is already attached to the object?

    Ideally I would love to make 2 different animations one for walking right, one for walking left and made them happening if the right arrow or left are clicked.
    Cannot find any documentation to do this. Any help/links?

    Thanks

  • http://www.rocket5studios.com/ Tim Miller

    Hi, it sounds like you should learn some of the basics of using Unity, there are some good basic tutorials here: http://unity3d.com/support/resources/tutorials/

    I updated the tutorial to include a C# script that should do what you want – scroll up to the “Player Animation In Script” section above and look for the “update” section.

    You won’t ever need to modify the scripts that come with Sprite Manager. You will create your own scripts and attach them to your game objects.

  • Katrine

    I have some problems creating more than one sprite based on the method descriped. When I create the first sprite, it’s like the material of that one attach itself to the Sprite Material when I create the Atlas, making it impossible for me to use it again for the second object. What am I doing wrong?

    And nice tut btw :)

  • http://www.rocket5studios.com/ Tim Miller

    Hi, is it possible that you assigned the Atlas to one of the sprites instead of the Material? I’ve done that before and the result sounds like what you’re describing. So make sure you have “Sprite Material” from the Materials folder assigned and not “Sprite Material” from the Sprite Atlases folder. Hope that helps.

  • http://twitter.com/solidd_swa solidd_swa

    kinda still waiting for the next in the series here ^.^

  • http://www.rocket5studios.com/ Tim Miller

    Hi, sorry about the delay. I’ve been super busy getting my game ready to show at GDC. Hopefully I’ll be able to pick up the series again soon.

  • Pingback: Creating 2D Games With Unity3D Part 4 | Rocket 5 Studios

  • Pingback: Creating 2D Games with Unity3D Part 5 Complex Collision | Rocket 5 Studios

  • http://www.facebook.com/people/Keith-Bahrenburg/545250058 Keith Bahrenburg

    Excellent tutorial!

    I am having an issue with creating images that don’t take on their native size when put into Unity via SpriteManager2 (v1.84).

    I have followed all the steps to the best of my ability: Pixel Perfect and Auto Size are checked and the sprite looks like a near perfect quality version of my original. It just renders as a larger version of my original, which should be 54pixels wide at 72dpi, but the Unity sprite shows up as a 118pixel wide image (scaled proportionally).

    Does this have to do with the Camera Size you mention in Tutorial 1? I tried altering the camera size multiple times with no effect to the size of my sprite. (but I was able to find a size that matched the default cube to a 32x32pixel screenshot)

    Any help would be greatly appreciated!

  • http://www.facebook.com/people/Keith-Bahrenburg/545250058 Keith Bahrenburg

    To clarify the above issue… when I select the Sprite Material it reports it at the right size, 54 px wide, but the sprite in the Game Window takes up 118 px wide.

    Thoughts?

  • http://www.rocket5studios.com/ Tim Miller

    Hi.  Do you have have Non Power of 2 for each sprite .png set to “none”?  Also check that the Sprite Material in the Sprite Atlases folder is set to Override for Web and you have it set to ARGB 32 bit.  If it’s not, the texture will sometimes be non-square.

    Also every time you change the Camera Size (I assume you’re talking about the Orthographic size), you need to Build Atlases.

  • http://www.facebook.com/people/Keith-Bahrenburg/545250058 Keith Bahrenburg

    Yes, all of the above has been done as far as I can tell.

    Non Power of 2 is set to “None”, Sprite Material is set to Override for Standalone  with Max Size 1024 and Texture Format set to ARGB 32bit. My Camera Size is set to 12 and I Rebuilt the Atlasses after all of these changes.

    (also Mip Maps are unchecked, Filtering has been set to Point, default settings for building atlases are being used)

    A default cube is seen at 32 x 32 pixels when I screenshot and examine in Photoshop. My 54pixel wide sprite when screenshot and examined in Photoshop is still 118 for some weird reason… I can also visually tell that it’s larger in relationship to the Game Window area which is set to 1024 x 768.

  • http://www.rocket5studios.com/ Tim Miller

    Hmm… very strange.  If you send me an example project maybe I can figure it out.  Maybe send a simple project that has just 1 sprite?

  • http://www.facebook.com/people/Keith-Bahrenburg/545250058 Keith Bahrenburg

    Wow, that would be amazing if you’re truly up for that. (I promise not to continually hassle you about my sprite issues)

    How should I get you a sample project of the problem?

  • http://www.rocket5studios.com/ Tim Miller

    Just .zip it up and email to tim@rocket5studios.com

    I can’t guarantee that I can fix the problem, but I’ll give it a shot.  :)

  • http://www.facebook.com/people/Keith-Bahrenburg/545250058 Keith Bahrenburg

    Actually I think I may see what could be the problem…

    The original texture import is showing “Non Power of 2″ set to “None”

    However, the actual Sprite Material in the Sprite Atlases folder is showing it as “ToNearest” but it’s grayed out so I can’t change it…

    Any ideas?

  • http://www.rocket5studios.com/ Tim Miller

    That’s normal.  The sprite atlas always has “ToNearest” selected and grayed out.  Overriding and changing the texture format to “rgba 32 bit” or “truecolor” will allow the atlas to be non-square.

  • http://www.facebook.com/people/Keith-Bahrenburg/545250058 Keith Bahrenburg

    Done and done. Let me know if you find anything I missed. And seriously, thanks again for checking it out.

  • Thiago123456

    Hello, your tutorials are very well written.Can be very clear.Sorry for my bad english, I’m from Brazil.Continue with these great tutorials.Thank you.

  • Pingback: Tutorial: Developing 2D Games With Unity 3D « g4m3d3v

  • Pingback: Creating 2D Games With Unity3D Part 1 | Rocket 5 Studios

  • Pingback: New post format / 5 more hours per day could help… « GFX47's blog

  • Emanuel_kael

    I have a problem with this code:public class Controls : MonoBehaviour {

    public PackedSprite playerSprite; // assign your sprite to this in Unity
    public float moveSpeed = 2f;
    private float movement;

    void Update() {
    movement = Input.GetAxis(“Horizontal”) * moveSpeed;
    movement *= Time.deltaTime;
    transform.Translate(movement,0.0f, 0.0f); // move player along X axis

    // move right
    if(movement > 0.02f) {
    playerSprite.PlayAnim(0);
    }

    // move left
    if(movement < -0.02f) {
    playerSprite.PlayAnim(1);
    }
    }
    }the problem is this :Assets/NewBehaviourScript.js(1,23): BCE0043: Unexpected token: :.

  • http://www.rocket5studios.com/ Tim Miller

    Hi, In the error “Assets/NewBehaviourScript.js(1,23)”, the first number in perenthesis (1,23) is the line number.  So the error is on line 1 of your script.

    The problem is that the script is named Controls within the script itself (as it should be), but in Unity the script is named NewBehaviourScript.  Simply rename the script in Unity to Controls.

  • Thankful

    Hi: I don’t notice anything that says “override for iphone”, but I do have “override for web” and “override for standalone”.  Must I check these instead?  Thanks.

  • http://www.rocket5studios.com/ Tim Miller

    Hi. “override for iphone” will only show up as an option if you’re using the iPhone version of Unity.  So you can just choose one of the other options depending on if you’re building the game for the web or standalone.

  • Pingback: Make A 2D Game in Unity3D Using Only Free Tools Part 1 | Rocket 5 Studios

  • Pingback: 2D Or Not 2D – Creating 2D Games With Unity3D Part 3 | Rocket 5 Studios

  • Casper Nymose

    Great tutorial, but when I import my sprite, I still have the white background, even though my image in photoshop has no background. What do I do to remove it?

  • http://www.facebook.com/vlad.milyutin.5 Vlad Milyutin

    Now, Tools->AB Software->Build Atlases

  • henz

    Hi sir. I’m searching for free SM2 because I’m a student. =) Lucky and I found a link where can download it for free but I have doubt. Is these is the same as SM2 you using sir? Thank you. Sorry for my question. I just want to be sure.
    http://www.mediafire.com/download/p2f9g63md8gwepd/SpriteManager2_1.9.zip

  • http://www.rocket5studios.com/ Tim Miller

    I’m not certain, but I think that link you posted is to a pirated version of Sprite Manager 2 so you really shouldn’t use that. If you’re looking for a free sprite manager (SM2 is paid), I suggest you check out either Orthello Free http://www.wyrmtale.com/products/unity3d-components/orthello or Sprite Kit which is even easier to use https://github.com/prime31/SpriteKit

    If you use Orthello, check out this tutorial: http://www.rocket5studios.com/tutorials/skillswap-making-a-2-player-2d-game-with-unity/

    But if you’re new to Unity, I suggest you try Sprite Kit as it’s much simpler to use. I’m hoping to do a new tutorial someday that focuses on Sprite Kit.

  • NightWolf

    can u make a tutorial for Unity 4.3 native 2d tools?

  • Pingback: Unity good links | tuananhcode