Значение int отнимается рандомно

Рейтинг: 1Ответов: 1Опубликовано: 02.07.2023

у меня проблема со значением current ammo, оно вместо того чтобы отниматься по 1, отнимается в рандомном значений как можно это исправить. Я лишь только начинаю работать с С# и самим движком Unity, так что прошу простить за банальные вещи.

Часть кода в которой как я думаю допущена ошибка:

 void Shoot() 
{     
    currentAmmo --;
    if (Time.time > nextfire && !currentlyReloading)  
    for (int i = 0; i < amountOfBullets; i++)
    {
        nextfire = Time.time + TimeCouldown;
        GameObject bullet = Instantiate(bulletPrefab, firepoint.position, firepoint.rotation);
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
        Vector2 dir = transform.rotation * Vector2.up;
        Vector2 pdir = Vector2.Perpendicular(dir) * Random.Range(-spread, spread);
        rb.velocity = (dir + pdir) * BulletForce;        
        ShootAnimator.SetTrigger("Shoot");
    }
}

Весь код:

{        
    public float offset;              
    public Transform firepoint;                    // Точка из которой вылетает пуля
    public GameObject bulletPrefab;                // Объект пули используемый для стрельбы
    public Animator ShootAnimator;                // Анимация применяемая к оружию
    public int amountOfBullets;                    // Количество пуль вылетающее из точки вылета
    public float spread, BulletForce = 1f;         // Разброс пуль и скорость пули
    public float TimeCouldown;                     // Время ожидания, перед следующим выстрелом
    float nextfire;
    public float Range;

    public int maxAmmo = 5;
    public int currentAmmo;
    public bool currentlyReloading = false;
    public float reloadTime = 5f;


void start()
{
    if (currentAmmo == -1)
        currentAmmo = maxAmmo;
}

// Update is called once per frame    
void Update()
{     
    if (currentlyReloading)
        return;

    if (currentAmmo <= 0)
    if (Input.GetKey(KeyCode.R))
    {
        StartCoroutine(Reload());
        return;
    }

    Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
    float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.AngleAxis(angle + offset, Vector3.forward);
    if(Input.GetMouseButton(0))
    {
        Shoot();
    }    
}

void Shoot() 
{     
    currentAmmo --;
    if (Time.time > nextfire && !currentlyReloading)  
    for (int i = 0; i < amountOfBullets; i++)
    {
        nextfire = Time.time + TimeCouldown;
        GameObject bullet = Instantiate(bulletPrefab, firepoint.position, firepoint.rotation);
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
        Vector2 dir = transform.rotation * Vector2.up;
        Vector2 pdir = Vector2.Perpendicular(dir) * Random.Range(-spread, spread);
        rb.velocity = (dir + pdir) * BulletForce;        
        ShootAnimator.SetTrigger("Shoot");
    }
}

IEnumerator Reload()      
{
    currentlyReloading = true;
    ShootAnimator.SetBool("Reload", true);
    yield return new WaitForSeconds(reloadTime - .25f);
    ShootAnimator.SetBool("Reload", false);
    yield return new WaitForSeconds(.25f);        
    currentAmmo = maxAmmo;
    currentlyReloading = false;
   }
}

Ответы

▲ 2Принят

currentAmmo --; стоит снаружи if (Time.time > nextfire && !currentlyReloading) а функция Shoot вызывается каждый кадр который нажата кнопка. Этот код должен работать:

void Shoot() 
{     
    if (Time.time > nextfire && !currentlyReloading) {
        currentAmmo --;
        for (int i = 0; i < amountOfBullets; i++)
        {
            nextfire = Time.time + TimeCouldown;
            GameObject bullet = Instantiate(bulletPrefab, firepoint.position, firepoint.rotation);
            Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
            Vector2 dir = transform.rotation * Vector2.up;
            Vector2 pdir = Vector2.Perpendicular(dir) * Random.Range(-spread, spread);
            rb.velocity = (dir + pdir) * BulletForce;        
            ShootAnimator.SetTrigger("Shoot");
        }
    }
}