Search Unity

Question How to make shooting animation work

Discussion in 'Animation' started by LinkingLink14, Mar 27, 2023.

  1. LinkingLink14

    LinkingLink14

    Joined:
    Apr 22, 2022
    Posts:
    9
    Hi;

    I have been making an FPS game, and wanted to add some shooting animations to my gun. I have tried to code it into my script, but it doesn't work. Is there a good way to fix this?

    /code
    using System;
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    using TMPro;

    public class Gun : MonoBehaviour{

    [Header("Gun Settings")]
    public float damage = 10f;
    public float range = 100f;
    public float fireRate = 15f;
    public float impactForce = 30f;

    public int maxAmmo = 10;
    public int currentAmmo;
    public float reloadTime = 1f;
    private bool isReloading = false;
    private bool isScoping = false;
    private bool isFiring = false;

    [Header("Gun Assets")]
    public Camera fpscamera;
    public ParticleSystem muzzleflash;
    public GameObject impactEffect;

    private float nextTimeToFire = 0f;

    public Animator animator;

    [Header("UI")]
    public TextMeshProUGUI ammoDisplay;

    void Start ()
    {
    currentAmmo = maxAmmo;
    }

    void OnEnable ()
    {
    isReloading = false;
    animator.SetBool("Reloading", false);

    isScoping = false;
    animator.SetBool("Scoping", false);

    isFiring = false;
    animator.SetBool("Firing", false);
    }

    // Update is called once per frame
    void Update ()
    {
    ammoDisplay.text = currentAmmo.ToString() + "/" + maxAmmo;

    if (isReloading)
    {
    return;
    }


    if (currentAmmo <= 0)
    {
    StartCoroutine(Reload());
    return;
    }

    if (Input.GetKeyDown(KeyCode.R) && isReloading == false)
    {
    if(currentAmmo == maxAmmo)
    {
    return;
    }
    else;
    {
    StartCoroutine(Reload());
    return;
    }

    }

    if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
    {
    nextTimeToFire = Time.time + 1f / fireRate;
    Shoot();
    }

    }

    IEnumerator Reload ()
    {
    isReloading = true;
    Debug.Log("Reloading...");

    animator.SetBool("Reloading", true);

    yield return new WaitForSeconds(reloadTime);

    animator.SetBool("Reloading", false);

    currentAmmo = maxAmmo;
    isReloading = false;
    }
    /code