using System.Collections.Generic; using Unity.FPS.Game; using Unity.FPS.Gameplay; using UnityEngine; namespace Unity.FPS.UI { public class WeaponHUDManager : MonoBehaviour { [Tooltip("UI panel containing the layoutGroup for displaying weapon ammo")] public RectTransform AmmoPanel; [Tooltip("Prefab for displaying weapon ammo")] public GameObject AmmoCounterPrefab; PlayerWeaponsManager m_PlayerWeaponsManager; List m_AmmoCounters = new List(); void Start() { m_PlayerWeaponsManager = FindObjectOfType(); DebugUtility.HandleErrorIfNullFindObject(m_PlayerWeaponsManager, this); WeaponController activeWeapon = m_PlayerWeaponsManager.GetActiveWeapon(); if (activeWeapon) { AddWeapon(activeWeapon, m_PlayerWeaponsManager.ActiveWeaponIndex); ChangeWeapon(activeWeapon); } m_PlayerWeaponsManager.OnAddedWeapon += AddWeapon; m_PlayerWeaponsManager.OnRemovedWeapon += RemoveWeapon; m_PlayerWeaponsManager.OnSwitchedToWeapon += ChangeWeapon; } void AddWeapon(WeaponController newWeapon, int weaponIndex) { GameObject ammoCounterInstance = Instantiate(AmmoCounterPrefab, AmmoPanel); AmmoCounter newAmmoCounter = ammoCounterInstance.GetComponent(); DebugUtility.HandleErrorIfNullGetComponent(newAmmoCounter, this, ammoCounterInstance.gameObject); newAmmoCounter.Initialize(newWeapon, weaponIndex); m_AmmoCounters.Add(newAmmoCounter); } void RemoveWeapon(WeaponController newWeapon, int weaponIndex) { int foundCounterIndex = -1; for (int i = 0; i < m_AmmoCounters.Count; i++) { if (m_AmmoCounters[i].WeaponCounterIndex == weaponIndex) { foundCounterIndex = i; Destroy(m_AmmoCounters[i].gameObject); } } if (foundCounterIndex >= 0) { m_AmmoCounters.RemoveAt(foundCounterIndex); } } void ChangeWeapon(WeaponController weapon) { UnityEngine.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(AmmoPanel); } } }