Aiming Down Sights script stopped working

So I was following a tutorial for an Aim Down Sight script that initially worked. However after creating a script for the reload with animation I can no longer move the pistol to aim down sights.

Here is the scripts used in the Glock-18 Script:

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

public class Glock18 : MonoBehaviour
{
    private Vector3 originalPosition;
    public Vector3 aimPosition;
    public float adsSpeed = 8f;

    public int bulletsPerMag = 15;
    public int bulletsLeft = 150;
    public float range = 100f;
    public int currentBullets;
    private Animator anim;

    public ParticleSystem muzzleFlash;
    private AudioSource audioSource;
    public AudioClip shootSound;

    public Transform shootPoint;

    public float fireRate = 0.25f;

    float fireTimer;

    private bool isReloading;

    void Start()
    {
        anim = GetComponent<Animator>();

        audioSource = GetComponent<AudioSource>();

        originalPosition = transform.localPosition;
        currentBullets = bulletsPerMag;
    }

    void Update()
    {
        if (Input.GetButton("Fire1"))
        {
            if (currentBullets > 0)
            {
                Fire();
            }
        }
        else if (currentBullets == 0)
        {
            DoReload();
        }

        if (Input.GetKeyDown(KeyCode.R))
        {
            if (currentBullets < bulletsPerMag && bulletsLeft > 0)
            {
                DoReload();
            }
        }

        if(fireTimer < fireRate)
        {
            fireTimer += Time.deltaTime;
        }

        AimDownSights();
    }

    private void AimDownSights()
    {
        if (Input.GetButton("Fire2") && !isReloading)
        {
            transform.localPosition = Vector3.Lerp(transform.localPosition, aimPosition, Time.deltaTime * adsSpeed);
            Debug.Log("Aiming");
        }
        else
        {
            transform.localPosition = Vector3.Lerp(transform.localPosition, originalPosition, Time.deltaTime * adsSpeed);
        }
    }

    private void FixedUpdate()
    {
        AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);

        isReloading = info.IsName("Reload");
        // if (info.IsName("Fire")) anim.SetBool("Fire", false);
    }

    private void Fire()
    {
        if (fireTimer < fireRate || currentBullets <= 0 || isReloading) return;

        RaycastHit hit;

        if (Physics.Raycast(shootPoint.position, shootPoint.transform.forward, out hit, range))
        {
            Debug.Log(hit.transform.name + " hit");
        }

        anim.CrossFadeInFixedTime("Fire", 0.1f);
        muzzleFlash.Play();
        PlayShootSound();

        currentBullets--;
        fireTimer = 0f;
    }

    public void Reload()
    {
        if (bulletsLeft <= 0) return;

        int bulletsToLoad = bulletsPerMag - currentBullets;
        int bulletsToDeduct = (bulletsLeft >= bulletsToLoad) ? bulletsToLoad : bulletsLeft;

        bulletsLeft -= bulletsToDeduct;
        currentBullets += bulletsToDeduct;
    }

    private void DoReload()
    {
        AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);

        if (isReloading) return;

        anim.CrossFadeInFixedTime("Reload", 0.01f);
    }


    private void PlayShootSound()
    {
        audioSource.clip = shootSound;
        audioSource.Play();
    }
}

The AimDownSights(); is for the Aiming and the DoReload(); is for reloading enimation as well as Reload(); for the actual refill which is triggered within the animation script.

And here is the ReloadState scripts for the reload animation:

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

public class ReloadState : StateMachineBehaviour
{
    public float reloadTime = 0.95f;
    bool hasReloaded = false;

    // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        hasReloaded = false;
    }

    // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
    override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        if (hasReloaded) return;
        
        if(stateInfo.normalizedTime >= reloadTime)
        {
            animator.GetComponent<Glock18>().Reload();
            hasReloaded = true;
        }
    }

    // OnStateExit is called when a transition ends and the state machine finishes evaluating this state
    override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        hasReloaded = false;
    }

    // OnStateMove is called right after Animator.OnAnimatorMove()
    //override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    //{
    //    // Implement code that processes and affects root motion
    //}

    // OnStateIK is called right after Animator.OnAnimatorIK()
    //override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    //{
    //    // Implement code that sets up animation IK (inverse kinematics)
    //}
}

Please could somebody help me out? I am mostly new to unity and can’t figure this out.

PS: If I need to refine any of these to make it easier to see please tell me.

1 Answer

1

I think your issue might be that you have two conflicting functions. You are using the animator for reloading and hard coding the movement for aiming. If I were you, I would create an animation for aim, then have a condition where if you press the right mouse button down, it triggers the aim animation, and when you release the right mouse button, it returns to default (which could be the idle animation).


Also, this part is entirely up to you, but I’ve found it is easier to use Unity’s built-in Animator window, where you can create your state machine visually rather than with code. It depends on how much control you want to have over your animations, but the Animator has been just fine for every project I’ve worked on. Here are some resources for that if you’re interested.

Thank you, I tried this, although I definitely made it way more complicated than it needed to be but it works.