Strzelanie pociskami w Unity

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

public class PlayerShooting : MonoBehaviour
{
    [SerializeField] Transform aim;
    [SerializeField] GameObject bulletPrefab;
    [SerializeField] float bulletSpeed = 5f;

    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Shoot();
        }
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, aim.position, aim.rotation);
        bullet.GetComponent<Rigidbody2D>().velocity = transform.right * bulletSpeed;
    }
}

Display ammo amount in UI

using UnityEngine;
using UnityEngine.UI;

public class UIBulletDisplay : MonoBehaviour
{
    [SerializeField] Image imgMagAmmo;
    [SerializeField] Image imgTotalAmmo;
    
    public void DisplayBullets(int magAmount, int fillAmmo)
    {
        imgMagAmmo.fillAmount = magAmount / 50f;
        imgTotalAmmo.fillAmount = fillAmmo / 50f;
    }
}
using UnityEngine;

public class PlayerShooting : MonoBehaviour
{
    [SerializeField] UIBulletDisplay uIBulletDisplay;

    [SerializeField] Transform aim;
    [SerializeField] GameObject bulletPrefab;
    [SerializeField] float bulletSpeed = 5f;
    [SerializeField] int ammoTotal = 60;
    [SerializeField] int magCap = 10;

    AudioSource audioSource;

    int magTemp;

    private void Awake()
    {
        audioSource = GetComponent<AudioSource>();
    }

    private void Start()
    {
        magTemp = magCap;
        DisplayAmmoInfo();
    }

    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Shoot();
        }

        if (Input.GetButtonDown("Fire2"))
        {
            Reload();
        }
    }

    void Shoot()
    {
        if(magTemp > 0)
        {
            GameObject bullet = Instantiate(bulletPrefab, aim.position, aim.rotation);
            bullet.GetComponent<Rigidbody2D>().velocity = transform.right * bulletSpeed;
            audioSource.Play();
            magTemp--;
            DisplayAmmoInfo();
        }
    }

    void Reload()
    {
        int reloadAmount = magCap - magTemp;
        if(reloadAmount <= ammoTotal)
        {
            magTemp += reloadAmount;
            ammoTotal -= reloadAmount;
        }
        else
        {
            magTemp += ammoTotal;
            ammoTotal = 0;
        }
        DisplayAmmoInfo();
    }

    void DisplayAmmoInfo()
    {
        uIBulletDisplay.DisplayBullets(magTemp, ammoTotal);
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        AmmoCollect ammoCollect = collision.gameObject.GetComponent<AmmoCollect>();
        if(ammoCollect != null)
        {
            ammoTotal += ammoCollect.Collect();
            DisplayAmmoInfo();
        }
        Destroy(collision.gameObject);
    }
}
Scroll to Top