Basic shooting in Unity

This post is about how to add simple shooting functionality in Unity.
We will use a bullet prefab with Rigidbody2D component and Instantiate() method to add the bullet and make it fly.
In this example we also use a basic particle system to add shooting flash.

Our machine gun object has 2 children objects. First empty child is an aim, the other child is a particle system.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shoot : MonoBehaviour
{
    [SerializeField] GameObject bulletPrefab;
    [SerializeField] Transform aim;
    ParticleSystem ps;
    void Start(){
        ps = GetComponentInChildren<ParticleSystem>();
    }

    void Update(){
        if(Input.GetButtonDown("Fire1")){
            ps.Play();
            ShootBullet();
        }
    }

    void ShootBullet(){
        GameObject bullet = Instantiate(bulletPrefab, aim.position, Quaternion.identity);
        bullet.GetComponent<Rigidbody2D>().AddForce(new Vector2(10f, 0f), ForceMode2D.Impulse);
    }
}

Files to download:

Leave a Comment

Your email address will not be published. Required fields are marked *