How to implement a weapon-switching system in Unity (Part 2)
In this Answer, we’ll explore how to add a weapon-switching system in Unity. Such a feature is crucial for action and adventure games, giving players the flexibility to switch tactics and keeping the gameplay interesting. We’ll guide you through setting this up, step by step, enhancing the game’s dynamics and player experience.
This Answer is part of the introductory series on how to build a first-person shooter game using Unity.
Let’s dive into what we’ll be creating together in this tutorial.
Throughout this Answer, we’ll walk you through the essential steps to implement a weapon switching system in your Unity game. Starting with setting up the scene, we’ll then move on to creating unique weapon prefabs, each with its distinct characteristics. Following this, we’ll integrate a player inventory system to enable seamless switching between weapons using simple key presses. This tutorial is designed to not only introduce us to the basics of weapon switching but also to provide practical insights into managing multiple game assets and enhancing player interaction within our Unity project.
Step 1: Set up the Scene
To start, create a new Unity 3D project and set up a Scene for the game. The default Scene includes a “Main Camera” along with a directional light. If we already have a Scene, we can start with that instead. We’ll be modifying the Scene from the Implement Shooting Game Logic Answer.
Step 2: Create weapon prefabs
To incorporate a variety of firearms into our game, it’s necessary to develop distinct weapon prefabs. Each prefab will have its unique model, firing mechanics, and specific attributes. For this tutorial, we’ll use the weapon created in the Implement Shooting Game Logic Answer as a starting point. Simply duplicate this weapon and modify the Material’s color from red to green to differentiate them.
Note: Remember, our aim is to dynamically generate these weapons in the game, which is why we’ll be focusing on creating prefabs for each type of firearm.
Step 3: Player inventory
We want two weapons to switch on button click.
“Press 1”: Red weapon
“Press 2”: Green weapon
Create a script to manage the player’s inventory of weapons. This script should keep track of the player’s current weapon and the list of available weapons. We can use an array or a list to store references to the weapon prefabs.
using System.Collections;using System.Collections.Generic;using UnityEngine;public class WeaponSwitching : MonoBehaviour{public GameObject[] weaponPrefabs;private GameObject currentWeapon;void Start(){currentWeapon = Instantiate(weaponPrefabs[0], transform);currentWeapon.SetActive(true);}void Update(){// Detect input to switch weapons (you can customize this based on your game controls)if (Input.GetKeyDown(KeyCode.Alpha1)){Debug.Log("1 pressed");SwitchWeapon(0);}else if (Input.GetKeyDown(KeyCode.Alpha2)){SwitchWeapon(1);}}void SwitchWeapon(int index){if (index >= weaponPrefabs.Length || index < 0)return;// Destroy the current weapon and instantiate the new oneDestroy(currentWeapon);currentWeapon = Instantiate(weaponPrefabs[index], transform);currentWeapon.SetActive(true);}}
Lines 7–8:
weaponPrefabsis an array of GameObjects. It should be set in the Inspector to store different weapon prefabs that can be switched. Morever,currentWeaponis a reference to the currently active weapon GameObject.Lines 10–14: Sets the initial weapon by instantiating the first weapon prefab from the
weaponPrefabsarray and activating it.Lines 16–28: The
Updatemethod is another Unity callback that is called every frame. It detects the player’s input to switch weapons. If the player presses the “1” key (KeyCode.Alpha1), it calls theSwitchWeaponmethod with index0to switch to the first weapon. If the player presses the “2” key (KeyCode.Alpha2), it switches to the second weapon by calling theSwitchWeaponmethod with index 1.Lines 31–41: The
SwitchWeaponmethod is responsible for switching weapons. It accepts anindexparameter that represents the index of the weapon to switch to. The method first checks if the provided index is within a valid range (between 0 and the length of the weaponPrefabs array minus 1). If the index is outside this valid range, the method exits by using thereturnstatement. If theindexis valid, it destroys the current weapon usingDestroy, instantiates the new weapon specified by the index from theweaponPrefabsarray, sets it as the newcurrentWeapon, and finally activates the new weapon by callingSetActive(true).
Step 4: Attach the script
Attach the WeaponSwitching script to the Player GameObject. Drag and drop the weapons to the “Weapon Prefab” list.
In the Update method of the WeaponSwitching script, we need to detect player input to switch weapons. In this example, we use the number keys (1, 2, etc.) to switch between weapons, but we can customize this based on our game’s controls.
Now, when we play the game, we should be able to switch between different weapons by pressing the corresponding number keys. Each weapon should have its own behavior, shooting mechanics, and appearance, providing the player with a variety of options during gameplay.
Play here!
Note: Click the “Run” button below to start the game. Once the game is rendered, interact with it by clicking on the “Output” screen. Alternatively, you can access the game by clicking the link provided after “Your app can be found at:”
import React from 'react';
require('./style.css');
import ReactDOM from 'react-dom';
import App from './app.js';
ReactDOM.render(
<App />,
document.getElementById('root')
);
In the next Answer, we’ll be improving the game environment and giving it a Martian look. Stay tuned!
Next: How implement a Martian-looked skybox in Unity
Free Resources