How to make your Gun and Bullet system for your Unity Game and attach it to FPS Player Controller



This is a basic tutorial about making gun and bullet projectile system for your Unity games.

First I showed you how to make a bullet object, making it moving at certain speed, then making it as a prefab so we can fire any amount of bullets as we wish.

Then I showed you how to make a gun object, how to instantiate the bullet at gun position and matching it’s orientation (rotation).

As I said, everything you see here is the basic concept. There are a lot of things need to be done to improve it, such as adding sound effect, adding appropriate gun and bullet meshes, adding muzzle flashes, etc.

About the FPS controller, you can download it from free by watching this previous video: https://www.youtube.com/watch?v=0W8rDJyp5QI The download link is in that video description.

Scripts used in this video:

TNBullet.cs

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

public class TNBullet : MonoBehaviour
{
	
	public float bulletSpeed = 10f;
	public float destroyAfterSeconds = 5f;
	
	Rigidbody bullet;
	
    // Start is called before the first frame update
    void Start()
    {
        bullet = GetComponent<Rigidbody>();
		GameObject playersGun = GameObject.Find("GunObject");
		transform.position = playersGun.transform.position;
		transform.rotation = playersGun.transform.rotation;
    }

    // Update is called once per frame
    void Update()
    {
		if(destroyAfterSeconds > 0f){
			bullet.velocity = transform.forward * bulletSpeed;
			destroyAfterSeconds -= Time.deltaTime;
		}else{
			Destroy(gameObject);
		}
    }
}

TNGun.cs

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

public class TNGun : MonoBehaviour
{
	
	public GameObject bulletPrefab;
	
	public void FireTheBullet(){
		Instantiate(bulletPrefab, new Vector3(0,0,0), Quaternion.identity);
	}
	
}
loading...

Leave a Reply

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