using UnityEngine; using UnityEngine.UI; public class Weapon : MonoBehaviour { [Header("Weapon Settings")] public GameObject bulletPrefab; public Transform gunTip; public Camera playerCamera; public float bulletSpeed = 50f; public float bulletSpread = 0.1f; public float range = 100f; public LayerMask hitLayer; [Header("Bullet Hole Settings")] public GameObject bulletHolePrefab; public Material bulletHoleMaterial; public float bulletHoleLifetime = 5f; [Header("Weapon General Settings")] public string weaponName; public int damage = 10; public float fireRate = 0.2f; public bool isAutomatic = false; public int bulletsPerShot = 1; [Header("Ammo Settings")] public int reserveAmmo = 50; public Text ammoText; [Header("Effects")] public GameObject muzzleFlashPrefab; public AudioClip shootSound; [Header("Crosshair Settings")] public Sprite crosshairSprite; // 🔥 Unique crosshair for each weapon public Image crosshairUI; // 🔥 UI element for the crosshair private float lastShotTime = 0f; void Start() { UpdateAmmoUI(); UpdateCrosshair(); // 🔥 Set the crosshair when the weapon is equipped } void Update() { if (isAutomatic) { if (Input.GetMouseButton(0) && Time.time >= lastShotTime + fireRate) { Shoot(); } } else { if (Input.GetMouseButtonDown(0) && Time.time >= lastShotTime + fireRate) { Shoot(); } } } public void UpdateAmmoUI() { if (ammoText != null) ammoText.text = $"Ammo: {reserveAmmo}"; } public void UpdateCrosshair() { if (crosshairUI != null && crosshairSprite != null) { crosshairUI.sprite = crosshairSprite; // 🔥 Change the crosshair when switching weapons } } public void Shoot() { if (reserveAmmo <= 0) return; lastShotTime = Time.time; if (shootSound != null) { AudioSource audioSource = GetComponent<AudioSource>(); if (audioSource != null) audioSource.PlayOneShot(shootSound); } if (muzzleFlashPrefab != null) { GameObject muzzleFlash = Instantiate(muzzleFlashPrefab, gunTip.position, gunTip.rotation); Destroy(muzzleFlash, 0.1f); } for (int i = 0; i < bulletsPerShot; i++) { FireBullet(); } reserveAmmo -= bulletsPerShot; UpdateAmmoUI(); } public void AddAmmo(int amount) { reserveAmmo += amount; UpdateAmmoUI(); } private void FireBullet() { Vector3 screenCenter = new Vector3(Screen.width / 2, Screen.height / 2, 0); Ray ray = playerCamera.ScreenPointToRay(screenCenter); RaycastHit hit; Vector3 targetPoint = ray.GetPoint(range); if (Physics.Raycast(ray, out hit, range, hitLayer)) { targetPoint = hit.point; CreateBulletHole(hit); } } private void CreateBulletHole(RaycastHit hit) { if (bulletHolePrefab != null && bulletHoleMaterial != null) { GameObject bulletHole = Instantiate(bulletHolePrefab, hit.point + (hit.normal * 0.01f), Quaternion.LookRotation(-hit.normal)); bulletHole.transform.SetParent(hit.collider.transform); Projector projector = bulletHole.GetComponent<Projector>(); if (projector != null) { projector.material = new Material(bulletHoleMaterial); // Ensure material instance is unique } Destroy(bulletHole, bulletHoleLifetime); } } }