Files
PGiZ3/Assets/Code/Gameplay/Character/Inventory/WeaponInventory.cs
T
2026-02-24 10:33:33 +03:00

103 lines
3.1 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using Code.Gameplay.Weapons;
using System;
namespace Code.Gameplay.Character.Inventory
{
public class WeaponInventory : MonoBehaviour
{
[SerializeField] private List<WeaponBase> weapons = new();
[SerializeField] private Transform weaponHolder;
[SerializeField] private int currentWeaponIndex;
public event Action<WeaponBase> OnWeaponSwitched;
public event Action OnWeaponsInitialized;
public WeaponBase CurrentWeapon => weapons.Count > 0 ? weapons[currentWeaponIndex] : null;
public int WeaponCount => weapons.Count;
private void Start()
{
InitializeWeapons();
}
private void InitializeWeapons()
{
for (var i = 0; i < weapons.Count; i++)
{
weapons[i] = Instantiate(weapons[i].gameObject, weaponHolder).GetComponent<WeaponBase>();
weapons[i].gameObject.SetActive(false);
}
if (weapons.Count > 0 && currentWeaponIndex < weapons.Count)
{
weapons[currentWeaponIndex].gameObject.SetActive(true);
OnWeaponSwitched?.Invoke(weapons[currentWeaponIndex]);
}
OnWeaponsInitialized?.Invoke();
}
public void SwitchWeapon(int index)
{
if (index < 0 || index >= weapons.Count) return;
if (index == currentWeaponIndex) return;
weapons[currentWeaponIndex].gameObject.SetActive(false);
currentWeaponIndex = index;
weapons[currentWeaponIndex].gameObject.SetActive(true);
OnWeaponSwitched?.Invoke(weapons[currentWeaponIndex]);
}
public void NextWeapon()
{
var nextIndex = (currentWeaponIndex + 1) % weapons.Count;
SwitchWeapon(nextIndex);
}
public void PreviousWeapon()
{
var prevIndex = (currentWeaponIndex - 1 + weapons.Count) % weapons.Count;
SwitchWeapon(prevIndex);
}
public void RemoveWeapon(WeaponBase weapon)
{
if (weapons.Contains(weapon))
{
var index = weapons.IndexOf(weapon);
weapons.Remove(weapon);
Destroy(weapon.gameObject);
if (index <= currentWeaponIndex)
{
currentWeaponIndex = Mathf.Max(0, currentWeaponIndex - 1);
}
if (weapons.Count > 0)
{
weapons[currentWeaponIndex].gameObject.SetActive(true);
OnWeaponSwitched?.Invoke(weapons[currentWeaponIndex]);
}
}
}
public void ReloadCurrentWeapon()
{
CurrentWeapon?.Reload();
}
public void ShootCurrentWeapon()
{
CurrentWeapon?.StartShooting();
}
public void StopShootingCurrentWeapon()
{
CurrentWeapon?.StopShooting();
}
}
}