Home > Net >  Recoil animation boolean instantly goes to false
Recoil animation boolean instantly goes to false

Time:07-26

So I am trying to make it so that when the user shoots the recoil animation plays, but I have an issue where the bool (which goes true the moment the Fire() is called), instantly goes back to false. I have tried to remove the line of code which is supposed to only make the bool false once the user stopped firing the gun, but the result of that was just the recoil animation playing in a loop.

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

public class WeaponFire : MonoBehaviour
{
    public GameObject playerCam; // The player camera
    public float range = 150f;
    public float damage = 25f;
    public float rounds = 30f;
    public float mags = 3f;
    public GameObject FPS_char; // The gameobject that has the animator
    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        if (FPS_char.GetComponent<Animator>().GetBool("WeaponFire")) // Check to see if the player has fired
        {
            FPS_char.GetComponent<Animator>().SetBool("WeaponFire", false); // Set to false if true
        }
    }

    public void Fire()
    {
        
        // Shoot a ray
        RaycastHit hit;
        // Set the WeaponFire bool to true when Fire() is called, which is called when the player presses the left mouse button
        FPS_char.GetComponent<Animator>().SetBool("WeaponFire", true);
        // Create a ray
        if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out hit, range))
        {
            if (rounds <= 0)
            {
                // Player needs to reload
                return;
            }
            if(rounds >= 0)
            {         
                rounds -= 1f;
                gameObject.GetComponent<AudioSource>().Play(); // Play a weapon fire  sound
                EnemyManager enemyManager = hit.transform.GetComponent<EnemyManager>(); // A script that gives the enemies health and attack damage etc
                if (enemyManager != null) // check to see if what the player hit contains that script (if it does then it is an enemy)
                {
                    enemyManager.Hit(damage);  // Call the Hit() function of the script on the enemy which removes health from the enemy depending on how much damage the weapon does
                }
            }
        }
    }
    public void Reload()
    {
        mags -= 1f;
        rounds = 30f;
        // Add a reload animation
    }
}

CodePudding user response:

For things that need to play once use animator.SetTrigger which plays the animation when it is called once automatically. You need to change the Animator parameter from Bool to Trigger in the Animator window.

public void Fire()
{
    FPS_char.GetComponent<Animator>().SetTrigger("Fire");
}
  • Related