Sdílet prostřednictvím


Unity 2D: Sprites and Animation

This article is pulled from my website: https://42base13.net/ and article can also be read here: https://42base13.net/unity-2d-animation/

Introduction

People have asked me for a series of posts on Unity 2D to help them get started.  This tutorial series will go into a starters guide to Unity 2D for making simple games.  Years ago, I did an article for CodeProject.com called Invasion C# Style.  I took an article on DirectX and C++ and converted it over to Managed DirectX.  I am going to use the graphics from that game in this tutorial series since they are pretty decent graphics and work very well for a simple 2D game.

Unity is a cross platform game engine that has a built-in IDE for developing the game.  It uses C#, JavaScript, and Boo for scripts and uses MonoDevelop as the built in code editor.  Unity supports publishing to iOS, Android, Windows, BlackBerry 10, OS X, Linux, web browsers, Flash, PlayStation 3, Xbox 360, Windows 8, Windows Phone 8 and Wii U.  There has been talk of Unity supporting Xbox One and PlayStation 4 in the future as well.  Unity also includes a physic engine and as of the 4.3 version has support for making 2D games.  I have seen people make 2D games with Unity in 3D mode, but now it can support 2D directly.

Setup / Requirements

Make sure to get the latest version of Unity installed.  At the time that I am writing this, it is 4.3.2.

Visual Studio 2012/2013 is used for publishing only.  MonoDevelop 4 is installed and setup as the default editor for scripts.  You can change this in Unity by Going to Edit -> Preferences and then under External Tools you can change the External Script Editor.  You might have to browse for the devenv.exe file to get Visual Studio 2013 to show up, but it is not hard to find.

To publish to the Windows 8 Store or Windows Phone Store, you will need to sign up for a Developer account.  You can get an account for only $19 total for access to both stores.  If you have an MSDN account, BizSpark, or DreamSpark account, you can get into the store for free.

Let's Go...

Create 2D Project

When Unity is launched, a dialog pops up with two tabs Open Project and Create New Project.  Select the Create New Project tab and enter in a name for the project.  In the bottom left of the dialog, there is a dropdown for selecting 3D or 2D for the project.  Select 2D and then hit the Create button to make the project.

UnitysetupInvasion

The main Unity IDE will then come up.  This will now come up with the default 2D layout.  The lower left pane is the project pane that shows you all of the folders and the files for the project as well as the prefabs, scenes, and scripts.  The upper left pane is the hierarchy pane for the current scene being viewed.  The middle pane is the scene and the game pane where things can be moved and the game will run when you are debugging.  The far right pane is the inspector pane that will show the data for the selected item from the other panes.  The layout and position of the panes can be moved and if you select one of the options in the layer dropdown on the upper right of the window, then the positions will change.  To go back to this layout, select Default.

unityInvasionPanes

A Bit of Organizing

In the project pane, there is a folder names Assets.  This is actually a folder in the projects folder with the name Assets.  One thing that I like to do is to organize things a bit to make it easier to keep track of.  By right clicking on the Assets folder or on the pane to the right that says "This folder is empty", you can go to the Create -> Folder menu option to make folders to keep track of things. For this sample I am going to be making four folders, Artwork, Prefabs, Scenes, and Scripts.  This creates these folders under the Asset folder in the project's folder.

unityorganizing

Saving the Scene

One thing that helps at this point is to manually save the scene.  Select the File -> Save Scene menu option and then select the Scenes folder and save the scene, for this tutorial I named it MainScene.  This will create a MainScene.unity file in the Scenes folder.

unitysavescene

One thing to keep in mind working with Unity is to make sure that you have the correct scene open.  It is easy to have the wrong one open and you think there is something wrong with your project.  Keep this in mind.

Importing Images

Importing images into the project can be done in a few ways.  The first way is to find the folder under the project folder where you want the images and just copy them into that folder.  For this project, the Artwork folder s being used for images.  By taking the images from the CodeProject project, those can be dropped into the Artwork folder and when Unity regains the focus, the images are imported automatically.  The second way is to right click on the Artwork folder in the Project pane and use the Import New Asset... menu option.  A third way is to drag and drop the images to the folder in the Project pane and they will get copied into that folder.

For this part of the project, I copied over the background, the player ship, the three different ufo ships and the explosion images.

invasionsprites

When an image is selected in the Project pane, the Inspector pane will get filled in with details on the image.  Selecting the backdrop2 image will now give us the following information.

invasionbginspector

From this information, you can see a few things that are important.  The first is the Texture Type.  This will default to Sprite for all of the images that are imported.  The Sprite Mode defaults to Single. and the Pixels To Units defaults to 100.  If you want the image to be larger, then you can change the Pixels To Units value to a smaller number.  The Sprint Mode will be used when we make animations.

Adding Images to the Scene

At this point, we have nine images imported into our project and have a project setup for 2D and a scene named MainScene, but we don't have anything being displayed at all.  So the next step is to add our background to the scene so that we have something to see when we run the project.

From the Project pane, drag the backdrop2 image from the Artwork folder to the Scene pane right over the image of the camera. What this does is creates a GameObject named backdrop2 and adds the Sprite Renderer component to it.  With the Transform component, the scale, position, and rotation can be changed for the background.  One the Scene pane, the scroll wheel on the mouse will zoom the scene in and out to make it easier to see things.  This same thing can be done for anything that will be static in your game, such as a HUD, backgrounds, fixed buildings, etc.

invasionbg

Creating Animations

Games can be made with just static images and no animation, of course, that would not look very professional.  Good games have nice animations, transitions, and more.  Obviously, we want to make a good game, so it would be good to add some animations.  Plus, the sample project that I took the graphics from had sprite sheets for the player ship, all of the ufos, and the explosions.  Sprite sheets are a classic way to do animation in 2D games.  Unity has support built in to use sprite sheets and to create animations from those sprite sheets.  For this example, the ship, ufo, and explosion sprites all are sprite sheets.

If a sprite is a sprite sheet, the sprite mode will have to be changed to Multiple and this will add a Sprite Editor button.

invasionmulti

Going into the Sprite Editor you will see the entire sprite sheet appear in a new window.  In the upper left corner, there is a Slice button by default.  Clicking on this, will show a popup where the sprite will be edited into multiple images.

invasionedit1

After changing the Type to Grid, the display will change to show you the Pixel size for each sprite in the sprite sheet.  For the ones that included in the project, all sprites are 70x70 pixels.  From here, click on the Slice button and it will divide up the image into sprites with the size specified.

invasionedit2

Make sure to click on the Apply button on the upper right of this window to apply the slicing to the Sprite itself.  I have done this a few times where forgetting the Apply button means slicing the image again.  Do this to all of the Sprites to create multiple frame sprites that can be made into animations.

invasionedit3

At this point, we have a background on the display with the backdrop2 sprite and all of the other sprites are setup as multiple frame sprites.  If you expand the sprite in the Project pane, you will actually see all of the frames for the Sprite.  These frames are what is going to be used to create the animation.

invasionframes

Now to make the animations.  For a given sprite, expand the sprite to see all of the separate frames.  Select the frames and then drag them onto the Scene pane.  This will popup a dialog to create a new animation for you.  For the ship animation, I named it ShipAnimation.  In the Hierarchy pane, a new object named ship_0 is created.  This game object has the following properties when it is selected.  Notice that the Transform and Sprite Renderer are similar to what was seen with the background for the game.  A new component is added here for us called the Animator.  This is the component that will animate thru all of the frames.  From the main scene, you will only see the first frame of the animation, but if you click on the play button in the upper middle of the Unity IDE, you will be able to see the animation run.  In this tutorial, I am not going to be going over all of the separate options in each component.  This is left as an exercise for the reader.

invasionbgplayer

This will let us create animations for each of the sprite sheets by selecting the frames, dropping them on the scene, saving the animation file.  So we can see all of the sprites animate when we run the project.  Each of the sprites show up in the Hierarchy pane with the name of the first frame.  At this point to organize things better, the names in the Hierarchy pane are changed.  You will notice that the Artwork folder will have a lot of new files now.  An Animation folder could have been created to organize this better.

invasionall

Making a Prefab

Prefabs are pre-fabricated objects that have a set of properties and components that define how the object should behave.  Prefabs can be dynamically created in scripts.  To create a Prefab, just take drag the Sprite from the Hierarchy pane into the Prefab folder in the Project pane and it will create the prefab for you.  As you do this, you will notice that the game objects that are in the scene that are prefabs are colored in blue in the Hierarchy pane instead of the standard black.  For this examples, all of the ufos and explosions have been made into prefabs.

invasionprefabshier invasionprefabs

Since we have made prefabs from all of the ufos and explosions, we can actually remove the reference to them in the Hierarchy pane.  Once this is done, you will still see the prefabs in the Prefab folder, but the scene will not show any of the explosions or the ufos.  To get them on the screen, we will actually use a script for this.

Adding a C# Script

Scripting can be done using Javascript, C#, or Boo (a Python inspired syntax).  This will use C# since I am the most familiar with C#.  The first thing we will need to do is to add a new empty script.  Right click on the script folder and go to Create -> C# Script to make a new C# script.  This is named MainScript.  When it is selected in the Project pane, it will actually show the entire script in the Inspector pane.

invasionscript

Looking at the script, you will notice that it creates a public class using the name of the file that was created and it is derived from the MonoBehaviour class.  There are two methods that MonoBehaviour uses, Start and Update.  The Start method will be called when the script starts, so here you can put anything for setting things up.  The Update method will be called once per frame to display, move things, or whatever needs to be changed every frame.

To get the script running in our scene we need to add a new game object to the Hierarchy pane.  To add a new empty game object, use the GameObject -> Create Empty menu option.  This was renamed to MainScriptGameObject.  Now to tie the script to this game object, just drag the MainScript object from the Project pane to the new MainScriptGameObject in the Hierarchy pane.  This adds the script component to the game object itself.  Another way to add the script to a game object is to use the Add Component button and select Scripts -> MainScript.  This second method will show you all of the scripts in your project so that you can add any script easily.

Dynamically Adding Animated Sprites

Up to now, we have a main C# script and just our main player ship on the screen with our space background.  All of the other animations we changed to prefabs and are not getting displayed yet.  The next step is to edit the script and add the other animations back onto the scene dynamically.  This can be the first step in getting multiple enemies on the screen using the same prefab, setting up different levels, and enemy generation.  To start the editing of the script, double click on the script in the Project pane.  This will start up your default code editor which defaults to MonoDevelop.

The first thing that we need to do in the script is to create some public member variables to have the prefabs available in the script.  Once you save the script from the editor you will see these properties for the script in the Inspector pane when the MainScriptGameObject is selected in he Hierarchy pane.

Many .NET developers use properties now to do more data binding, but for Unity scripts, you have to use public members instead of properties.  Properties will not show up in the Inspector at all.  In the Project pane, switch to the Prefabs folder and then drop and drop the prefabs that you want to use to the script member variable.

invasionscript2

After this, when these member variables are used in the script, the prefabs will be used.  This makes it easy for us to add the prefabs dynamically to the scene.  The coordinates could be from an XML file, hard coded, or from any time of data storage.  For this example, we will hard code the positions for each animation.

To create an instance of the prefab, use the Instantiate method.  This will then need the prefab to use, the Vector3 for the position of the prefab and then the Quaternion.identity as parameters.  The following is used to show that multiple objects can be created using the same prefab in different locations.

 public class MainScript : MonoBehaviour {

    public GameObject PlayerExplode;
    public GameObject Ufo1;
    public GameObject Ufo2;
    public GameObject Ufo3;
    public GameObject Ufo1Explode;
    public GameObject Ufo2Explode;
    public GameObject Ufo3Explode;

    // Use this for initialization
    void Start () {
  Instantiate(PlayerExplode, new Vector3(0.5f, -1f), Quaternion.identity);
    Instantiate(Ufo1, new Vector3(-1.0f, 1.65f), Quaternion.identity);
  Instantiate(Ufo2, new Vector3(0f, 1.65f), Quaternion.identity);
 Instantiate(Ufo3, new Vector3(1.0f, 1.65f), Quaternion.identity);   
    Instantiate(Ufo1Explode, new Vector3(-1.0f, 0.65f), Quaternion.identity);
   Instantiate(Ufo2Explode, new Vector3(0f, 0.65f), Quaternion.identity);
  Instantiate(Ufo3Explode, new Vector3(1.0f, 0.65f), Quaternion.identity);    

    Instantiate(Ufo1, new Vector3(-2.0f, 1.65f), Quaternion.identity);
  Instantiate(Ufo1, new Vector3(-2.0f, 0.65f), Quaternion.identity);
    }
 
    // Update is called once per frame
    void Update () {
    }
}

Please keep in mind, save the script in the editor before you switch back to Unity to test your changes.  This has happened multiple times to me and some of my students.  It is easy to forget.  When you switch back to Unity it will reload the script just like it loaded the files when you added them to the folders under the Project's folder.

After exiting and restarting Unity, the Sprites were not showing up correctly.  This was due to the order of things being displayed.  All of the prefabs and the PlayerShip game objects were changed to have a value of 1 for the order of being displayed with the background set at the default value of 0.

Conclusion

At the end of all of these steps, we have a space background scene and have some animations on the screen and some that are added dynamically with a C# script.  This is the first step in getting your Sprites and Animations into Unity 2D to make a game.

This is the start of my tutorial series on Unity 2D.  More posts will come adding functionality to the game, documenting the steps as the Invasion game is developed using Unity 2D and getting published.  For each article, the source code will be available for download.  Feel free to use the code for your own research and as a basis for your own games, but please do not publish my game.  Use your creativity to make your own.

Source Download

The original sprites can be found in the Original Sprites folder and the full Unity Project on my GitHub project UnityInvasion.  Have fun.

Comments

  • Anonymous
    August 15, 2014
    I'm looking forward to reading all of them, thanks

  • Anonymous
    August 27, 2014
    I can't wait for the next one, either.