Pro_Unit

Weapon

Nov 13th, 2023
711
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. using System.Collections;
  2.  
  3. using UnityEngine;
  4.  
  5. public class Weapon : MonoBehaviour
  6. {
  7.     public Transform firePoint;
  8.     public GameObject bulletPrefab;
  9.     public float fireRate = 0.5f;
  10.     public int magazineSize = 30;
  11.     public float reloadTime = 2f;
  12.     public int damage = 10;
  13.     public ParticleSystem partSystem;
  14.     public int currentAmmo;
  15.     public Animator anim;
  16.     private bool isReloading = false;
  17.     private float nextFireTime = 1f;
  18.  
  19.     private void Start()
  20.     {
  21.         currentAmmo = magazineSize;
  22.     }
  23.  
  24.     private void Update()
  25.     {
  26.         if (isReloading)
  27.             return;
  28.  
  29.         if (Input.GetButton("Fire1"))
  30.         {
  31.             if (currentAmmo > 0 && Time.time >= nextFireTime)
  32.             {
  33.                 nextFireTime = Time.time + fireRate;
  34.                 Shoot();
  35.                 anim.SetTrigger("Shoot");
  36.             }
  37.             else
  38.             {
  39.                 StartCoroutine(Reload());
  40.             }
  41.         }
  42.  
  43.         if (Input.GetButtonDown("Reload") && currentAmmo < magazineSize)
  44.         {
  45.             anim.SetTrigger("Reload");
  46.             StartCoroutine(Reload());
  47.             nextFireTime = Time.time + fireRate;
  48.         }
  49.     }
  50.  
  51.     private void Shoot()
  52.     {
  53.         // Создаем пулю
  54.         GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
  55.  
  56.         // Получаем компонент "Target" из префаба пули
  57.         Target target = bullet.GetComponent<Target>();
  58.  
  59.         // Если у цели есть компонент "Target", наносим урон
  60.         if (target != null)
  61.         {
  62.             target.TakeDamage(damage);
  63.             Debug.Log("Bullet hit target!");
  64.         }
  65.         else
  66.         {
  67.             Debug.Log("Bullet did not hit target. Target component not found.");
  68.         }
  69.  
  70.         // Уменьшаем количество патронов
  71.         currentAmmo--;
  72.  
  73.         // Уничтожаем пулю через некоторое время (предотвращение утечек памяти)
  74.         Destroy(bullet, 2f);
  75.     }
  76.  
  77.     private IEnumerator Reload()
  78.     {
  79.         isReloading = true;
  80.         // Ждем время перезарядки
  81.         yield return new WaitForSeconds(reloadTime);
  82.  
  83.         // Перезаряжаем оружие
  84.         currentAmmo = magazineSize;
  85.         isReloading = false;
  86.     }
  87. }
  88.  
Advertisement
Add Comment
Please, Sign In to add comment