Jump to content
  • Advertisement
  • entries
  • comments
  • views

100 Days of VR: Day 16 Using A Real Gun Model In Unity

Josh Chang


Welcome back to Day 16! Today we’re going to go fix some of the assets for the game.

Specifically, today I want to:

  1. Use a real gun asset
  2. Add the shooting effect back in
  3. Create code to trigger reloading

Do you know what that means?

We’re going to go back to the Unity asset store to find new assets! Let’s get started!

Setting Up a Real Gun Asset

I looked around for a gun asset and I found a great machine gun model to use!

I found this great looking Machine Guns asset.


After downloading and loading the asset into our Unity game, you’ll find the files in the FreeMachineGun folder in the main project tab.

The first thing we should do is replace our cube with our gun asset.

In the folder FreeMachineGun: FreeMachineGun > Prefabs we find MachineGun_00. Drag the prefab into our hierarchy and make it a child of our Main Camera game object, making it the child of our previous Gun game object.

I made some configuration to my transform to make it fit here’s what I have, however you might have to eyeball it yourself.

  • Position: (0.25, -0.5, 0.75)
  • Rotation: (0. 90, 0)

You should have something like this:


I like how straightforward this is!

Setting up the Gun Animation to Run When We Shoot

Right now, when we left click, our gun will start shooting and spilling out ammos.

You might be thinking: “Wow! This model is amazing it even has the shooting code done for me!”

Unfortunately, it isn’t that easy. What we’re seeing is the particle effect of the gun that we activate in our PlayerShootingController.

You might also notice that after we shoot, our particle effect never stops either, that’s because in our code, we never had to stop our particle effect before.

Before we go in and fix this, let’s first understand the states to our animation.

For us to interact with the animation of a model, we must go to the Animatortab to set animation states and transitions.

Select MachineGun_00 in the hierarchy pane and then go to the Animatortab.

If the Animator tab isn’t available for you can find it in Window > Animator

Here’s what we see.


We have 3 trigger parameters to work with:

  • DoOpen
  • DoReload
  • Shoot

As for our state, we have 4 states:

  • Default
  • MachingGun_open
  • MachineGun_shoot
  • MachineGun_reload

Looking at our transitions…

In default:

  • Shoot transition to the MachineGun_shoot
  • DoOpen transitions to MachineGun_open
  • DoReload transitions to MachineGun_reload

In MachineGun_shoot

  • Shoot transition back to default
  • DoOpen transitions to MachineGun_open
  • DoReload transitions to MachineGun_reload

In MachineGun_open:

  • Shoot transition to the MachineGun_shoot
  • DoOpen transitions back to default
  • DoReload transitions to MachineGun_reload

In MachineGun_reload:

  • After the animation time is finish we transition to default

Now that we understand how the trigger logic works, we can work on the shooting script.

Now I don’t know what the DoOpen animation is for, however we don’t need it for the game in my mind. We just need to shoot and reload.

Creating the Code to Shoot

Now that we have the assets in place, we’re going to write the code to use it.

The first thing is that for some reason, I attached the PlayerShootingController to the camera. I’m going to move that to our new MachineGun_00 game object.

If you created a new PlayerShootingController, make sure the settings are:

  • Range: 100
  • Shooting Delay: 0.2
  • Shot Sfx Clips: Machine_Gunfire_01

Before going to the code, I had to think about the general cases that I would encounter for our animation to work.

It’s interesting to think about it, because we have 3 states that our gun can be in: default, shooting, and reloading. Now imagine how much more complicated if we had to transition between even more!

When I first started coding, I just had the general case, press R to reload and then shoot.

However, there were problems where my code would put me in permanent shooting animation mode among many other things.

There were some that I had to encounter, here were the specific animation cases I had to consider:

  1. Hit reload while we’re not doing anything
  2. Hit reload while we’re shooting
  3. Shoot while we’re reloading
  4. Never let go of our mouse before we shoot, reload, and then hold on until after we’re done reloading

Without any further waiting, here’s our code:

using UnityEngine;
public class PlayerShootingController : MonoBehaviour
    public float Range = 100;
    public float ShootingDelay = 0.1f;
    public AudioClip ShotSfxClips;
    private Camera _camera;
    private ParticleSystem _particle;
    private LayerMask _shootableMask;
    private float _timer;
    private AudioSource _audioSource;
    private Animator _animator;
    private bool _isShooting;
    private bool _isReloading;
    void Start () {
     _camera = Camera.main;
     _particle = GetComponentInChildren<ParticleSystem>();
     Cursor.lockState = CursorLockMode.Locked;
     _shootableMask = LayerMask.GetMask("Shootable");
     _timer = 0;
        _animator = GetComponent<Animator>();
        _isShooting = false;
        _isReloading = false;
    void Update ()
        _timer += Time.deltaTime;
        if (Input.GetMouseButton(0) && _timer >= ShootingDelay && !_isReloading)
            if (!_isShooting)
           else if (!Input.GetMouseButton(0))
            if (_isShooting)
        if (Input.GetKeyDown(KeyCode.R))
    private void StartReloading()
        _isShooting = false;
        _isReloading = true;
    private void TriggerShootingAnimation()
        _isShooting = !_isShooting;
    private void StopShooting()
    private void Shoot()
        _timer = 0;
        Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit = new RaycastHit();
        if (Physics.Raycast(ray, out hit, Range, _shootableMask))
            print("hit " + hit.collider.gameObject);
            EnemyHealth health = hit.collider.GetComponent<EnemyHealth>();
            EnemyMovement enemyMovement = hit.collider.GetComponent<EnemyMovement>();
            if (enemyMovement != null)
            if (health != null)
    // called from the animation finished
    public void ReloadFinish()
        _isReloading = false;
    private void SetupSound()
        _audioSource = gameObject.AddComponent<AudioSource>();
        _audioSource.volume = 0.2f;
        _audioSource.clip = ShotSfxClips;

There’s been a lot of changes and addition to the code, but in general here’s the flow:

  1. We created more variables to keep track of what state we’re in. Currently we’re using Booleans, however I think using Enums to represent our state might be a better idea, especially if we have more states to keep track of.
  2. In Start() we initialize our new boolean states
  3. In Update(), while we’re not reloading and we hit Shoot, if we haven’t started shooting, we’ll start our shooting animation in TriggerShootingAnimation() and we’ll run our shooting logic in Shoot()
  4. Whenever we let go of our mouse, we’ll go to the else statement in Update() and stop our shooting animation and run our stop shooting logic in StopShooting() which stops our music and particle effect
  5. A side note: in Shoot(), I started the particle effect when we hit something with the raycast, we want it to always run whenever we shoot.
  6. In Update() when we want to reload, we press R and we’ll go into StartReloading(), here we would trigger our reload animation to start and disable our shooting so the players can’t continue shooting.
  7. We have a public function ReloadFinish() that tells us we’re down reloading. We’re going to have to go to the animation for our machine gun and add an event to run this function whenever we’re done reloading.

So now that we have our code in place, let’s add the event into our reload animation to run our ReloadFinish() code when the animation finishes.

To do that, select MachineGun_00 and select the Animation tab.

If you don’t have the Animation tab, you can open it by going to Window -> Animation.

Here’s what we will have at the end:


In the animation tab:

  1. Select MachineGun_reload as our animation
  2. Go to frame 68
  3. Click the add event button below our frame number
  4. Select ReloadFinish() as the function to run once we get to that frame

With all of this in place, we’ll be able to reload now when we hit R and then resume normal shooting controls after the animation ends.


There we go! Today we added a real gun asset to replace our fake cube gun. As you can see, it wasn’t that bad and a lot of the things we did, we already learned from the Zombie Shooter tutorial we did at the end.

With our gun in place, we’re done now, right? WRONG!

Back when I was doing my Survival shooter post, Scouting Ninja commented to me on how shooting really works and it turns out that the raycast we create isn’t actually coming directly from the screen.

It’s coming from the muzzle of our gun to the middle of the screen.

Tomorrow, I’m going to investigate how to shoot a raycast from our gun muzzle instead of directly from our screen!

Until then, I’ll see you all in Day 17!

Source: Day 16

Visit the 100 Days of Unity VR Development main page.

Visit our Homepage



Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
  • Advertisement
  • Blog Entries

  • Similar Content

    • By Erz0
      Flappy Monster is back with a Remastered Version , new mechanics, graphics and rewards are waiting for you to come back.
      Touch and Fly , simple as that , mentain the rigidbody velocity of the flappy monster and get into a world full of danger. OZN , ASTEROIDS. You must protect yourself from danger !
      Don't worry , you have unlimited Ninja shurikens to throw into obstacles 

      1.0.1 VERSION NEW Features
      • NEW LEVELS
      • POWERS
      • COOL MUSIC
      • SHOP

      APP LINK: https://play.google.com/store/apps/details?id=com.erzo.flyingmonsterarcade
      Contact us at erz0development@gmail.com for errors, suggestions, business and privacy policy.
    • By khawk
      In a blog post yesterday, Unity announced new pricing for Unity Pro and Unity Plus subscriptions. The increase starts at the beginning of 2020 and does not affect existing Unity subscriptions. Any changes to current subscriptions, however, will end up being affected by the price increase.
      According to the blog, Unity is increasing prices "in order to continue investing in new technology, features and services that will benefit all Unity creators".
      Read more from the Unity blog here.

      View full story
    • By khawk
      In a blog post yesterday, Unity announced new pricing for Unity Pro and Unity Plus subscriptions. The increase starts at the beginning of 2020 and does not affect existing Unity subscriptions. Any changes to current subscriptions, however, will end up being affected by the price increase.
      According to the blog, Unity is increasing prices "in order to continue investing in new technology, features and services that will benefit all Unity creators".
      Read more from the Unity blog here.
    • By RoKabium Games
      Aura enemies – ”Heeble” is a spider-like creature that is closely related to the Creeble, Greeble and Beeble and it can crawl across any type of block. The ice-webs this one spins causes a lingering damage so stay clear and burn those webs from afar.
    • By Shadowsane
      My project started in 2014 but recently ended due to no funds.  AltarisNine was a Minecraft project based on RPG. The concept was nine islands that you explore at a time to follow an in depth lore based on our own production team. This is where the 'Nine' comes in. With skepticism of future success we hope to make this tale into chapters. Such as the first one introducing Nine islands at time.
      It wasn't always the same though, my world did evolve over time and now I have a better idea of what it is better than ever. In the first island, Main Isle, is themed around jungles and wilderness. There's lore that stretches throughout the chapter which will engage the player. There would also be kinds of characters you can be such as any other RPG which could be talked about (because i'm still  about what I have lol)
      My former team was designing a world players would get into interact with in various ways. Boss battles would be minigames and the RPG lore would be engaged in and something indie platforms would enjoy and talk about beyond platforms.
      In the minecraft varient I was a builder, the leader, and the story director which everyone respected. I led my own team of builders and story writers. While I chose certain individuals to be the head department of development and art design.
      The reason I am here is to find a new team to help take this away from minecraft and hope we can be successful about it. I'll happily commute each and every person that volunteers and will be accommodated down the line with promotions, wages, and definitely praised for helping start my dream up.

      Here are some questions that were frequently asked and that I can thoroughly answer:
      What is the goal of the game? If you've ever heard of Wizard101. I got inspired by that game a little. I like the concept of making yourself in this world of mystery and impressing people with new mechanics and events that they enjoy. I'd like for the game to be successful and be mostly on PC but if this keeps up we could reach out to other consoles. But for now, PC, one platform at a time lol. My goal personally is to give people the entertainment and enjoyment I think they'll deserve. Something thats not cheesy, not cliche, something new to keep evolving the gaming community Is this in first-person or third-person? This will be a third person game. We can play around with the camera angles but I kind of want it from a aerial pov I saw RPG in the post so can I assume that the game will have generic RPG elements, e.g. quests, npcs, story-line, items? Yes this will have generic RPG elements. But with a few surprises that make the game different. Such as making boss fights some type of minigame. I don't know how the audience will like or even if it'll flow with game play. But I'd still like to take the idea on for now. Will there be combats, e.g. vs. monsters, vs. players(?) ? There will be tons of concepts. As i've said before the 'Nine' comes in the Nine isles of this world we haven't named yet lol. Each nine islands we come up with will not only give players plenty of content to play, but something we break up into story chapters. Each island will have its on set monsters tied to the story or even monsters that are just natural in their environment. There will also be a PvP aspect which can't be brought up too much because its difficult to try to come up with a player style culture that isn't too predictable or generic or even cliche. I was wondering if it should be an initiated fight or a head on duel like world of warcraft. Is this a single player game or a multiplayer one? Definitely multiplayer. Will the game look like Minecraft? like a voxel/blocks game? I imagined it not looking like minecraft but maybe that can be a concept of its own down the line (like an island concept). I was thinking along the lines of a 3D style and not like minecraft. What are the core mechanics to be included, e.g. player movement, enemy movement, enemy AI? This question is more technical but there will be interactive things in the world, things to collect, natural occurring crafting supplies to make new loot and weapons with. There will be NPC's and thats a broad topic enough lol. I'd even a imagine a pet, housing, and gardening system. But thats for accessories in coding and to give more content in the game for later polishing. Is there a storyline already made? There is an indirect storyline. We've made a script for voice actors (and just what to make the NPC's say in general) in A9 v1. Are there goals already planned out? There are many goals to set out. One each at a time for separate upcoming departments The first 8 pictures were of our hub, the other 9 was our factions world. The factions world doesn't retain to this project I wanted you to see how dedicated I was to making this project. I built everything in the hub myself except for the giant pagodas. The last two photos were all the ones I could find of the RPG world

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!