Unity Basics Course: Implementing Shooting Functionality

Hello! In this blog post, I will explain in detail how to implement shooting functionality using the Unity engine. This tutorial will be beneficial for everyone, from those who are new to Unity to those who want to revisit the basics. We will proceed step by step, providing both code and explanations along the way. The goal of this tutorial is to understand and implement the basic shooting mechanics for a simple 2D or 3D shooting game.

1. Installing Unity and Basic Setup

To use Unity, you first need to install Unity Hub. Unity Hub is useful for managing multiple Unity projects and installing and updating various versions of the Unity engine.

  1. Download and install Unity Hub.
  2. After running Unity Hub, install the required Unity version. The recommended version is the latest LTS (Long Term Support) version.
  3. Once installed, create a new 3D or 2D project.

2. Understanding the Project Structure

A Unity project consists of various folders. The ‘Assets’ folder is where we store our resources (scripts, images, audio, etc.). The ‘Scenes’ folder stores the scenes, where each scene represents a stage or level of the game.

3. Creating a Basic Scene

First, let’s create a basic scene. We will add a simple plane to create a space for the player to shoot.

  1. Right-click in the Hierarchy view and select ‘3D Object’ > ‘Plane’ to add a plane.
  2. Adjust the Scale of the Plane to create a larger space.
  3. Adjust the position of the Camera to face the plane.

4. Creating the Player Character

To create the player character, we will add a new 3D object. Here, we will use a simple cube to represent the player.

  1. Right-click in the Hierarchy view and select ‘3D Object’ > ‘Cube’ to add a cube.
  2. Adjust the Scale of the Cube to (1, 2, 1) to shape it like the player.
  3. Name the Cube ‘Player’.
  4. Set the Y-axis of the Cube appropriately so that it is placed above the plane when the application runs (e.g., Y=1).

5. Implementing the Shooting Functionality

Now, let’s create a bullet that the player can shoot and implement the shooting functionality for it.

5.1. Creating the Bullet Prefab

To implement the bullet, let’s create a bullet prefab using a new cube.

  1. Add a new ‘Cube’ in the Hierarchy and name it ‘Bullet’.
  2. Adjust the Scale of the Bullet to (0.2, 0.2, 0.5) to shape it like a bullet.
  3. Add a Rigidbody component to the Bullet to enable physics.
  4. To make the Bullet a Prefab, drag the Bullet object into the ‘Assets’ folder.
  5. Now delete the Bullet Prefab from the Hierarchy.

5.2. Writing the Script

Now, we will write a script to allow the player to shoot. Create a new C# script in the ‘Assets’ folder and name it ‘PlayerController.cs’. Let’s write the following code.