Set up a 2D player character

Tutorial

·

Beginner

·

+0XP

·

25 mins

·

Unity Technologies

Set up a 2D player character

In this tutorial you’ll create a GameObject for the player character and add a custom script to it so you can control it using player inputs.

By the end of this tutorial, you’ll be able to do the following:

  • Create a GameObject using a sprite.
  • Describe how 2D positions are controlled in Unity.
  • Write a custom C# script to set a GameObject’s position using information stored in a variable.

1. Overview

Creating a character and setting it up to move in response to player input is a fundamental part of your 2D adventure game. Without a basic version of the character ready at the start of your development process, you won’t be able to test anything else that you work on, and iterative testing is a critical part of making any game.

In this tutorial, you’ll create a player character using a 2D sprite and move it in a placeholder game environment with code.

Note: For the purposes of this tutorial and the rest of the course, we chose to use the Ruby’s Adventure asset set, and the file paths used in instructions will reflect this. If you chose another asset set, the file names will be the same, but in your corresponding theme folder.

2. Create a new scene

Scenes are how your game is organized in Unity — one scene per small game or level is a good starting point for a beginner. To create your scene, follow these instructions:

1. In the Project window, go to Assets > _2DAdventureGame, then right-click and select Create > Folder, and rename it “Scenes”.

2. In the Scenes folder, right-click and select Create > Scene > Scene.

The Unity Editor with the Scenes folder selected (red highlight) in the Project window. The context menu is open, with the Create menu item selected (red highlight), and the Create submenu is open with the Scene menu item selected (red highlight).

Note: A dialog might warn you about unsaved changes in the current scene. If you encounter this, select Don’t Save.

3. Name your new scene “MainScene”.

4. Double-click the MainScene to open it in the Editor.

If prompted with a window stating “Do you want to save the changes you made in the scenes: SampleScene?”. Select Don’t Save.

3. Create a player character with a sprite

Before you begin to create a level, let’s explore some 2D basics by setting up the player character for your game.

A sprite is a 2D asset used to create your game visuals in Unity. You’ll work with a variety of sprites as you make your game. We’ve prepared three different sets of assets, including sprites, so that you can choose the theme of your adventure game.

You can also mix and match assets from these sets or find your own sprites to use if you want to!

To create a GameObject for the player character using a sprite, follow these instructions:

1. In the Project window, go to Assets > _2DAdventureGame > Art > [Your Chosen Project], and select the PlayerCharacter sprite.

2. In the Inspector window, ensure the Texture Type property is set to Sprite (2D and UI).

3. In the Scene view toolbar, confirm that 2D mode is enabled.

4. In the Project window, select the arrow icon on the PlayerCharacter asset to reveal the sprite that Unity created when the image was imported.

5. Drag the PlayerCharacter sprite from the Project window and release it over the Scene view to create a new GameObject.

Note: Make sure to place the PlayerCharacter sprite inside the camera bound rectangle in Scene view.

6. Select the Game tab to switch to the Game view — if your player character is inside the camera bounds, you’ll see it on a blue background. If the GameObject is outside the bounds, it won’t be visible at all.

Note: If you want to change the background color, select the Main Camera GameObject, and in its Camera component in the Inspector window, use the foldout (triangle) to expand the Environment section, set the Background Type property to Solid Color, and choose a color using the Background property’s color picker.

7. Select the Scene tab to return to the Scene view, then from the main menu, select File > Save or use the shortcut Ctrl+S (macOS: Cmd+S) to save your changes.

We’ll remind you to save when it’s particularly important, but you should develop a habit of regularly saving as you work on any project in Unity!

4. Set an initial player character position

Next, you’ll position the PlayerCharacter GameObject within the scene. Since you’re making a 2D game, you only need to focus on the horizontal and vertical axes. Positions on these axes are represented as coordinate pairs (X,Y) — for example (2,-4).

You can set a GameObject’s position by updating its Transform component. First, you need to check that the camera is centered in the scene. To do this, follow these instructions:

1. In the Hierarchy window, select the Main Camera GameObject.

2. In the Inspector window, go to the Transform component and check that the Position property’s X and Y values are set to (X = 0 and Y = 0).

These values mean that the GameObject is at the center of the scene.

Screenshot showing the Transform component, with a callout for the Position property and its values

Note: Ignore the Z value (depth)—as this is a 2D game—depth is not relevant and we will only work in the X and Y axes.

3. Press F to focus your view on the Main Camera GameObject at the center of the scene.

Important: If your cursor is not in the Scene view, this focus action will not work.

Next, you’ll position your PlayerCharacter GameObject so it appears closer to the center of the screen.

4. In the Hierarchy window, select your PlayerCharacter GameObject.

5. In the Inspector window, in the Transform component, set the following Position property values:

  • X = -2
  • Y = 0

Tip: If you find it difficult to visualize positions before you make the change, image the GameObject on the axes of a graph. Negative values will move a GameObject to the left on the horizontal x-axis or down on the vertical y-axis.

6. Save your changes.

5. Create a new script

The first script that you’ll create for this game will control the player character’s movement, which is a key functionality for the game.

To create a new script, follow these instructions:

1. In the Project window, go to Assets > _2DAdventureGame.

2. Right-click and select Create > Folder, and name the new folder “Scripts”.

3. Open the Scripts folder, then right-click and select Create > Scripting > MonoBehaviour Script.

4. Name the new script “PlayerController”.

5. Double-click the PlayerController script to open the script file in your default integrated development environment (IDE).

This will be Visual Studio unless you have set an alternative default IDE on your computer.

Important: If the code doesn't open in your IDE, follow these instructions to add modules for your Unity version.

Refresh your memory of the default script content

Before you continue with this tutorial, it’ll be useful to review some basics about the default content in new scripts:

  • For now, you can ignore the using instruction at the top of the script (line 1). This type of instruction defines the namespaces that the script can access. A namespace is a grouping of code that contains particular systems or functionality — it’s a way to keep everything as organized as possible. You’ll need to add the correct namespace to a script when you want to access features and systems that aren’t included in the Unity Editor by default.
  • The PlayerController public class is the new component that you’re writing. A class is a way to organize code that contributes to a particular component or controls a particular system. You’re going to add instructions that tell the computer what this component needs to do within the braces of this class ({}).
  • There are two functions within the class for the component: Start and Update. Functions are a way to group related instructions, and these two functions relate to when the computer will perform the instructions. The instructions in each function are contained within another pair of braces. You’ll learn more about these functions as you work through this course.

If these explanations feel confusing, we recommend completing the Junior Programmer pathway, where you’ll build a solid foundation in C# coding and Unity programming fundamentals.

6. Add code to make the player character move

You’re going to add code to the PlayerController script that will be attached to the PlayerCharacter GameObject. This won’t be the final version of the script — it’s just a starting point to help you understand the basics of changing a GameObject’s Transform position through code.

To begin writing the code, follow these instructions:

1. Find the Update function.

This particular function is called each frame—which means that the instructions in it are executed constantly while the game is running.

2. Add the following line of code inside the Update function:

Vector2 position = transform.position;

Here’s an explanation of this line of code:

  • This instruction declares (creates) a new variable called position. Variables are named places that you can store data so that you can retrieve the data when you need to. You can think of a variable like a locker or cupboard with a name on it.
  • The variable’s type is Vector2. Different variable types can store different data. The Vector2 type can store two numerical values, so it’s ideal for 2D coordinates.
  • The equal sign (=) tells the computer what to store in the variable.
  • transform.position tells the computer to store the X and Y values of the Position property contained within the Transform component. You can use the dot (called the dot operator) to access data that’s contained within another object or component. This instruction stores the current position of the GameObject.
  • The semicolon (;) tells the computer that the instruction is finished. If you don’t include it, an error message will display in the Unity Editor Console window and the code won’t work.

3. Add the following line of code inside the Update function, underneath the first line:

position.x = position.x + 0.1f;

Based on the previous instruction that you wrote, what do you think this instruction does? Take a moment to try and work it out before reading on.

Here’s an explanation of this line of code:

  • This instruction sets a new horizontal (x-axis) position for the GameObject.
  • You’ve accessed the x-coordinate value stored within the position variable that you declared in the previous instruction.
  • The equals sign (=) tells the computer to store a new value for the x-coordinate.
  • The new position for the coordinate is the current position (position.x) plus 0.1. f indicates a number with a decimal place (called a floating point number).

4. Add the following line of code inside the Update function, underneath the second line:

transform.position = position;

What do you think this instruction does? Take a moment to consider before reading on!

Here’s an explanation of this line of code:

  • This instruction sets the Position property in the Transform component using your position variable.
  • Previously, the updates that you made were being stored in your variable, but they hadn’t been applied to the GameObject. This instruction will actually make the player character move.

5. Save your script changes, by pressing Ctrl+S (macOS: Cmd+S), then return to Unity Editor.

7. Test your changes

Now you’re ready to test your code! To apply the script and check your work, follow these instructions:

1. In the Hierarchy window, select the PlayCharacter GameObject.

2. In the Inspector window, select Add Component. Search for and add the PlayerController (Script) component. Alternatively, you can drag the script icon from the Project window and release it over Add Component in the Inspector window to assign it to the GameObject.

Screenshot showing the Player Controller (Script) component attached to the PlayerCharacter  GameObject, with a callout for the Add Component button

3. Save your changes.

4. Select the Play button to enter Play mode and test the script.

Note: Sometimes, while working in the Inspector or running your game, you might see some warnings appear in the Console. It’s a good habit to read and understand what they say, as they can help you catch small mistakes or potential issues early. However, some warnings are harmless or temporary and can be cleared by simply clicking the "Clear" button in the top-left corner of the Console window.

The player character should move right very quickly to the right and disappear offscreen!

Note: Remember to exit Play mode when you’re done.

8. More things to try

If you want to further develop your skills, explore new concepts, or improve your project, check out some of the optional activities below. Each one is tagged as either Easy, Medium, or Difficult, so you can choose the level of challenge.

These activities are entirely optional, so if you’re not interested, no problem — just skip this step. We do recommend attempting at least one of them in order to get the most out of this learning experience. Good luck!

Easy: Switch to vertical movement

You’ve used one axis to move the PlayerCharacter GameObject — try to switch to the other axis to make the movement vertical instead of horizontal.

Medium: Move the GameObject on both axes

You now have all the knowledge that you need to move the PlayerCharacter GameObject simultaneously on both axes. Try to add another instruction to the Update function to achieve this!

Difficult: Reduce the PlayerCharacter speed

Try to adjust the code that you’ve already written so the PlayerCharacter GameObject moves more slowly.

9. Check your script

Take a moment to check that your script is correct before continuing.

PlayerController.cs

Important: If you completed any extension work in your script, this will not be reflected in the reference script below.

using UnityEngine;

public class PlayerController : MonoBehaviour

{

	// Start is called once before the first execution of Update after the MonoBehaviour is created

	void Start()

	{

	}

	// Update is called once per frame

	void Update()

	{

	Vector2 position = transform.position;

	position.x = position.x + 0.1f;

	transform.position = position;

	}

}


10. Next steps

In this tutorial you’ve set up basic movement for the player character. Next, you’ll create a basic gameplay environment for the player character to move around.

Complete this tutorial