Files
3D-FPS/3D FPS/Assets/Scripts/Gun/Gun.cs

81 lines
2.1 KiB
C#
Raw Normal View History

2024-12-08 11:56:39 +01:00
using System.Collections;
using System.Collections.Generic;
2024-12-10 20:44:03 +01:00
using TMPro;
2024-12-08 11:56:39 +01:00
using UnityEngine;
using UnityEngine.Events;
public class Gun : MonoBehaviour
{
public UnityEvent onGunShoot;
public float fireCoolDown;
public bool automatic;
2024-12-10 20:44:03 +01:00
public int ammo;
public float reloadCooldown;
2024-12-08 11:56:39 +01:00
private float currentCooldown;
2024-12-10 20:44:03 +01:00
private float currentReloadCooldown;
private int currAmmo;
2024-12-08 11:56:39 +01:00
2024-12-10 20:44:03 +01:00
public AudioSource audioSource;
public AudioClip reloadSound;
public TextMeshProUGUI ammoTxt;
2024-12-08 11:56:39 +01:00
void Start()
{
currentCooldown = fireCoolDown;
2024-12-10 20:44:03 +01:00
currAmmo = ammo;
ammoTxt.text = currAmmo.ToString() + "/" + ammo.ToString();
2024-12-08 11:56:39 +01:00
}
void Update()
{
if(automatic)
{
if(Input.GetMouseButton(0))
{
2024-12-10 20:44:03 +01:00
if(currentCooldown <= 0f && currentReloadCooldown <= 0f && currAmmo != 0)
2024-12-08 11:56:39 +01:00
{
//if not null (?)
onGunShoot?.Invoke();
currentCooldown = fireCoolDown;
2024-12-10 20:44:03 +01:00
currAmmo--;
ammoTxt.text = currAmmo.ToString() + "/" + ammo.ToString();
2024-12-08 11:56:39 +01:00
}
}
}
else
{
if(Input.GetMouseButtonDown(0))
{
2024-12-10 20:44:03 +01:00
if(currentCooldown <= 0f && currentReloadCooldown <= 0f && currAmmo != 0)
2024-12-08 11:56:39 +01:00
{
//if not null (?)
onGunShoot?.Invoke();
currentCooldown = fireCoolDown;
2024-12-10 20:44:03 +01:00
currAmmo--;
ammoTxt.text = currAmmo.ToString() + "/" + ammo.ToString();
2024-12-08 11:56:39 +01:00
}
}
}
2024-12-10 20:44:03 +01:00
if(Input.GetKeyDown(KeyCode.R))
{
if(currentReloadCooldown <= 0f)
{
currAmmo = ammo;
currentReloadCooldown = reloadCooldown;
audioSource.PlayOneShot(reloadSound);
ammoTxt.text = currAmmo.ToString() + "/" + ammo.ToString();
}
}
2024-12-08 11:56:39 +01:00
currentCooldown -= Time.deltaTime;
2024-12-10 20:44:03 +01:00
currentReloadCooldown -= Time.deltaTime;
2024-12-08 11:56:39 +01:00
}
}