| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UIElements;
- using UnityEngine.SceneManagement;
- using System.Linq;
- public class ItemShopManager : MonoBehaviour
- {
- [Header("Shop Settings")]
- public string shopName = "General Store";
- [Header("Shop Items (ScriptableObjects)")]
- [SerializeField] private List<Item> availableItems = new List<Item>();
- private UIDocument uiDocument;
- private TeamCharacter currentCustomer;
- // Callback for when character data changes
- public System.Action<TeamCharacter> OnCharacterDataChanged;
- // UI Elements
- private VisualElement shopContainer;
- private TextField searchField;
- private DropdownField categoryFilter;
- private DropdownField customerDropdown;
- private ScrollView itemList;
- private Label shopTitle;
- private Label playerMoney;
- private Button closeButton;
- // Current filter state
- private string currentCategory = "All";
- private string currentSearchTerm = "";
- void Awake()
- {
- // Load all Item ScriptableObjects from Resources
- LoadAllItems();
- }
- void Start()
- {
- // Use a coroutine to delay initialization by one frame
- // This ensures other scripts that might modify UIDocument have finished
- StartCoroutine(DelayedInitialization());
- }
- private IEnumerator DelayedInitialization()
- {
- // Wait one frame to ensure all other Start() methods have completed
- yield return null;
- // Get all UIDocument components to debug
- UIDocument[] allUIDocuments = GetComponents<UIDocument>();
- Debug.Log($"Found {allUIDocuments.Length} UIDocument components on this GameObject");
- // Initialize UI in Start() to ensure UIDocument is ready
- uiDocument = GetComponent<UIDocument>();
- if (uiDocument == null)
- {
- Debug.LogWarning("ItemShopManager: No UIDocument component found. Shop UI will be initialized when needed.");
- // Try to find UIDocument on parent or children as fallback
- uiDocument = GetComponentInParent<UIDocument>();
- if (uiDocument == null)
- {
- uiDocument = GetComponentInChildren<UIDocument>();
- }
- if (uiDocument != null)
- {
- Debug.Log("Found UIDocument on parent/child, using that instead");
- }
- else
- {
- Debug.Log("No UIDocument found anywhere in hierarchy. Will create one when shop is opened.");
- yield break; // Exit gracefully instead of throwing an error
- }
- }
- if (uiDocument.visualTreeAsset == null)
- {
- Debug.LogWarning("ItemShopManager: UIDocument needs a Visual Tree Asset assigned! Will try to load when shop is opened.");
- yield break;
- }
- // Load and apply stylesheet
- var stylesheet = Resources.Load<StyleSheet>("UI/TownShopUI");
- if (stylesheet != null)
- {
- uiDocument.rootVisualElement.styleSheets.Add(stylesheet);
- Debug.Log("✓ ItemShopManager: Stylesheet loaded successfully");
- }
- else
- {
- Debug.LogWarning("⚠ ItemShopManager: Could not load TownShopUI stylesheet from Resources/UI/");
- }
- // Ensure panel settings and proper sorting order are set
- EnsurePanelSettings();
- InitializeUI();
- }
- void LoadAllItems()
- {
- availableItems.Clear();
- // Load all Item ScriptableObjects from Resources/Items folder and subfolders
- Item[] allItems = Resources.LoadAll<Item>("Items");
- if (allItems.Length == 0)
- {
- Debug.LogWarning("No Item ScriptableObjects found in Resources/Items folder. Creating some default items...");
- CreateDefaultItems();
- }
- else
- {
- availableItems.AddRange(allItems);
- }
- // Also check for items in the direct Resources folder
- Item[] directItems = Resources.LoadAll<Item>("");
- foreach (Item item in directItems)
- {
- if (!availableItems.Contains(item))
- {
- availableItems.Add(item);
- }
- }
- Debug.Log($"Total items available in shop: {availableItems.Count}");
- }
- void CreateDefaultItems()
- {
- // Create some default items if none are found
- // These will be temporary runtime items, but you should create proper ScriptableObject assets
- // Note: This creates runtime instances, not asset files
- var simpleSword = ScriptableObject.CreateInstance<WeaponItem>();
- simpleSword.itemName = "Basic Sword"; // Match actual asset name
- simpleSword.description = "A basic sword for beginners.";
- simpleSword.itemType = ItemType.Weapon;
- simpleSword.goldCost = 10;
- simpleSword.minDamage = 1;
- simpleSword.maxDamage = 6;
- simpleSword.weaponType = WeaponType.Sword;
- simpleSword.searchTags = new string[] { "sword", "melee", "blade", "basic" };
- availableItems.Add(simpleSword);
- var simpleBow = ScriptableObject.CreateInstance<WeaponItem>();
- simpleBow.itemName = "Basic Bow"; // Match actual asset name
- simpleBow.description = "A basic bow for shooting arrows.";
- simpleBow.itemType = ItemType.Weapon;
- simpleBow.goldCost = 15;
- simpleBow.minDamage = 1;
- simpleBow.maxDamage = 4;
- simpleBow.range = 150;
- simpleBow.weaponType = WeaponType.Bow;
- simpleBow.searchTags = new string[] { "bow", "ranged", "arrow", "basic" };
- availableItems.Add(simpleBow);
- var leatherArmor = ScriptableObject.CreateInstance<ArmorItem>();
- leatherArmor.itemName = "Leather Armor";
- leatherArmor.description = "Basic leather protection.";
- leatherArmor.itemType = ItemType.Armor;
- leatherArmor.goldCost = 12;
- leatherArmor.armorClass = 1;
- leatherArmor.armorType = ArmorType.Light;
- leatherArmor.armorSlot = ArmorSlot.Chest;
- leatherArmor.searchTags = new string[] { "leather", "armor", "chest", "light" };
- availableItems.Add(leatherArmor);
- var healthPotion = ScriptableObject.CreateInstance<MiscellaneousItem>();
- healthPotion.itemName = "Health Potion";
- healthPotion.description = "Restores health when consumed.";
- healthPotion.itemType = ItemType.Consumable;
- healthPotion.goldCost = 3;
- healthPotion.isConsumable = true;
- healthPotion.healthDiceCount = 1;
- healthPotion.healthDiceType = 6;
- healthPotion.healthBonus = 1;
- healthPotion.searchTags = new string[] { "potion", "health", "healing", "consumable" };
- availableItems.Add(healthPotion);
- Debug.Log("Created default runtime items since no ScriptableObject assets were found.");
- }
- private bool SetupUIDocument()
- {
- // Try to get UIDocument component
- uiDocument = GetComponent<UIDocument>();
- if (uiDocument == null)
- {
- // Add UIDocument component if it doesn't exist
- uiDocument = gameObject.AddComponent<UIDocument>();
- }
- // Try to load the TownShopUI asset
- var shopUIAsset = Resources.Load<VisualTreeAsset>("UI/TownShopUI");
- if (shopUIAsset == null)
- {
- Debug.LogError("Could not load TownShopUI.uxml from Resources/UI/");
- return false;
- }
- uiDocument.visualTreeAsset = shopUIAsset;
- // Load and apply stylesheet
- var stylesheet = Resources.Load<StyleSheet>("UI/TownShopUI");
- if (stylesheet != null)
- {
- uiDocument.rootVisualElement.styleSheets.Add(stylesheet);
- Debug.Log("✓ ItemShopManager: Stylesheet loaded successfully");
- }
- // Ensure panel settings
- EnsurePanelSettings();
- return true;
- }
- private void InitializeUI()
- {
- var root = uiDocument.rootVisualElement;
- // Use the correct element names from TownShopUI.uxml
- shopContainer = root.Q<VisualElement>("shop-container");
- searchField = root.Q<TextField>("search-field");
- categoryFilter = root.Q<DropdownField>("category-filter");
- customerDropdown = root.Q<DropdownField>("customer-dropdown");
- itemList = root.Q<ScrollView>("item-list");
- shopTitle = root.Q<Label>("shop-name");
- playerMoney = root.Q<Label>("money-label");
- closeButton = root.Q<Button>("close-button");
- // Debug which elements were found
- // Setup category filter
- if (categoryFilter != null)
- {
- categoryFilter.choices = new List<string> { "All", "Weapons", "Armor", "Consumables", "Tools", "Accessories", "Miscellaneous" };
- categoryFilter.value = "All";
- categoryFilter.RegisterValueChangedCallback(OnCategoryChanged);
- }
- // Setup customer dropdown (will be populated when opening shop)
- if (customerDropdown != null)
- {
- // Initialize with empty choices to prevent index errors
- customerDropdown.choices = new List<string>();
- customerDropdown.RegisterValueChangedCallback(OnCustomerChanged);
- }
- // Setup search field
- if (searchField != null)
- {
- searchField.RegisterValueChangedCallback(OnSearchChanged);
- }
- // Setup close button
- if (closeButton != null)
- {
- closeButton.clicked += CloseShop;
- }
- // Hide shop initially
- if (shopContainer != null)
- {
- shopContainer.style.display = DisplayStyle.None;
- Debug.Log("ItemShopManager: Shop initially hidden");
- }
- }
- public void OpenShop(TeamCharacter customer)
- {
- if (customer == null)
- {
- Debug.LogError("Cannot open shop: customer is null");
- return;
- }
- Debug.Log($"ItemShopManager: Opening shop for {customer.name}");
- // Ensure UIDocument is initialized
- if (uiDocument == null)
- {
- uiDocument = GetComponent<UIDocument>();
- }
- if (uiDocument == null)
- {
- Debug.LogError("ItemShopManager: UIDocument component not found! Please add a UIDocument component to this GameObject.");
- Debug.LogError($"GameObject name: {gameObject.name}");
- return;
- }
- if (uiDocument.visualTreeAsset == null)
- {
- Debug.LogError("ItemShopManager: UIDocument needs a Visual Tree Asset assigned! Please assign ShopUI.uxml");
- return;
- }
- // Ensure UI is initialized
- if (shopContainer == null)
- {
- Debug.Log("ItemShopManager: UI not initialized, attempting to set up...");
- // Try to set up UIDocument if not already done
- if (uiDocument == null)
- {
- if (!SetupUIDocument())
- {
- Debug.LogError("ItemShopManager: Could not set up UIDocument. Cannot open shop.");
- return;
- }
- }
- InitializeUI();
- }
- if (shopContainer == null)
- {
- Debug.LogError("ItemShopManager: shopContainer is null! Make sure TownShopUI.uxml is assigned to the UIDocument and contains a 'shop-container' element.");
- return;
- }
- currentCustomer = customer;
- // Update customer dropdown
- UpdateCustomerDropdown();
- // Update UI
- if (shopTitle != null)
- {
- shopTitle.text = shopName;
- }
- UpdatePlayerMoney();
- RefreshItemList();
- // Show shop
- if (shopContainer != null)
- {
- shopContainer.style.display = DisplayStyle.Flex;
- }
- Debug.Log($"Opened {shopName} for {customer.name}");
- }
- public void CloseShop()
- {
- if (shopContainer != null)
- {
- shopContainer.style.display = DisplayStyle.None;
- }
- currentCustomer = null;
- }
- private void OnCategoryChanged(ChangeEvent<string> evt)
- {
- currentCategory = evt.newValue;
- RefreshItemList();
- }
- private void OnSearchChanged(ChangeEvent<string> evt)
- {
- currentSearchTerm = evt.newValue;
- RefreshItemList();
- }
- private void RefreshItemList()
- {
- if (itemList == null) return;
- itemList.Clear();
- var filteredItems = GetFilteredItems();
- foreach (var item in filteredItems)
- {
- var itemElement = CreateItemElement(item);
- itemList.Add(itemElement);
- }
- }
- private List<Item> GetFilteredItems()
- {
- var filteredItems = new List<Item>(availableItems);
- // Apply category filter
- if (currentCategory != "All")
- {
- ItemType filterType;
- switch (currentCategory)
- {
- case "Weapons":
- filterType = ItemType.Weapon;
- break;
- case "Armor":
- filterType = ItemType.Armor;
- break;
- case "Consumables":
- filterType = ItemType.Consumable;
- break;
- case "Tools":
- filterType = ItemType.Tool;
- break;
- case "Accessories":
- filterType = ItemType.Accessory;
- break;
- case "Miscellaneous":
- filterType = ItemType.Miscellaneous;
- break;
- default:
- filterType = ItemType.Miscellaneous;
- break;
- }
- filteredItems = filteredItems.Where(item => item.itemType == filterType).ToList();
- }
- // Apply search filter
- if (!string.IsNullOrEmpty(currentSearchTerm))
- {
- filteredItems = filteredItems.Where(item => item.MatchesSearch(currentSearchTerm)).ToList();
- }
- return filteredItems;
- }
- private VisualElement CreateItemElement(Item item)
- {
- var itemContainer = new VisualElement();
- itemContainer.AddToClassList("shop-item");
- // Item name
- var nameLabel = new Label(item.itemName);
- nameLabel.AddToClassList("item-name");
- itemContainer.Add(nameLabel);
- // Item description with stats
- string description = item.description;
- string statsString = GetItemStatsString(item);
- if (!string.IsNullOrEmpty(statsString))
- {
- description += $" {statsString}";
- }
- var descriptionLabel = new Label(description);
- descriptionLabel.AddToClassList("item-description");
- itemContainer.Add(descriptionLabel);
- // Price and buy button container
- var priceButtonContainer = new VisualElement();
- priceButtonContainer.style.flexDirection = FlexDirection.Row;
- priceButtonContainer.style.justifyContent = Justify.SpaceBetween;
- priceButtonContainer.style.alignItems = Align.Center;
- var costLabel = new Label(item.GetCostString());
- costLabel.AddToClassList("item-price");
- priceButtonContainer.Add(costLabel);
- // Purchase button
- var purchaseButton = new Button(() => PurchaseItem(item));
- purchaseButton.text = "Buy";
- purchaseButton.AddToClassList("buy-button");
- priceButtonContainer.Add(purchaseButton);
- itemContainer.Add(priceButtonContainer);
- // Check if player can afford the item
- bool canAfford = currentCustomer != null && CanCustomerAfford(item);
- purchaseButton.SetEnabled(canAfford);
- if (!canAfford)
- {
- purchaseButton.AddToClassList("purchase-button-disabled");
- }
- itemContainer.Add(purchaseButton);
- return itemContainer;
- }
- private string GetItemStatsString(Item item)
- {
- var statStrings = new List<string>();
- if (item is WeaponItem weapon)
- {
- statStrings.Add($"Damage: {weapon.minDamage}-{weapon.maxDamage}");
- if (weapon.range > 0)
- statStrings.Add($"Range: {weapon.range}");
- if (weapon.weaponModifier != 0)
- statStrings.Add($"Weapon Mod: {weapon.weaponModifier:+0;-0}");
- }
- else if (item is ArmorItem armor)
- {
- if (armor.armorClass > 0)
- statStrings.Add($"AC: +{armor.armorClass}");
- if (armor.strengthModifier != 0)
- statStrings.Add($"STR: {armor.strengthModifier:+0;-0}");
- if (armor.dexterityModifier != 0)
- statStrings.Add($"DEX: {armor.dexterityModifier:+0;-0}");
- if (armor.constitutionModifier != 0)
- statStrings.Add($"CON: {armor.constitutionModifier:+0;-0}");
- if (armor.wisdomModifier != 0)
- statStrings.Add($"WIS: {armor.wisdomModifier:+0;-0}");
- }
- else if (item is MiscellaneousItem misc && misc.isConsumable)
- {
- if (misc.healthDiceCount > 0)
- {
- string healthEffect = $"Heals {misc.healthDiceCount}d{misc.healthDiceType}";
- if (misc.healthBonus != 0)
- healthEffect += $"{misc.healthBonus:+0;-0}";
- statStrings.Add(healthEffect);
- }
- else if (misc.healthRestoreMin > 0 || misc.healthRestoreMax > 0)
- {
- statStrings.Add($"Heals {misc.healthRestoreMin}-{misc.healthRestoreMax}");
- }
- if (misc.manaDiceCount > 0)
- {
- string manaEffect = $"Restores {misc.manaDiceCount}d{misc.manaDiceType}";
- if (misc.manaBonus != 0)
- manaEffect += $"{misc.manaBonus:+0;-0}";
- statStrings.Add($"{manaEffect} mana");
- }
- else if (misc.manaRestoreMin > 0 || misc.manaRestoreMax > 0)
- {
- statStrings.Add($"Restores {misc.manaRestoreMin}-{misc.manaRestoreMax} mana");
- }
- }
- return statStrings.Count > 0 ? string.Join(", ", statStrings) : "";
- }
- private void PurchaseItem(Item item)
- {
- if (currentCustomer == null)
- {
- Debug.LogError("No customer set!");
- return;
- }
- // Check if customer can afford the item directly
- if (!CanCustomerAfford(item))
- {
- Debug.LogWarning($"Cannot afford {item.itemName}");
- return;
- }
- // Calculate and deduct the cost
- DeductItemCost(item);
- // Add item to customer's inventory (you'll need to implement this based on your inventory system)
- AddItemToCustomerInventory(item);
- // Refresh UI
- UpdatePlayerMoney();
- RefreshItemList();
- // Notify listeners that character data changed
- OnCharacterDataChanged?.Invoke(currentCustomer);
- Debug.Log($"Successfully purchased {item.itemName}");
- }
- private bool CanCustomerAfford(Item item)
- {
- if (currentCustomer == null) return false;
- int totalCopperCost = item.goldCost * 100 + item.silverCost * 10 + item.copperCost;
- int totalCopperAvailable = currentCustomer.gold * 100 + currentCustomer.silver * 10 + currentCustomer.copper;
- return totalCopperAvailable >= totalCopperCost;
- }
- private void DeductItemCost(Item item)
- {
- // Convert everything to copper for easier calculation
- int totalCopperCost = item.goldCost * 100 + item.silverCost * 10 + item.copperCost;
- int totalCopperAvailable = currentCustomer.gold * 100 + currentCustomer.silver * 10 + currentCustomer.copper;
- int remainingCopper = totalCopperAvailable - totalCopperCost;
- // Convert back to gold, silver, copper
- currentCustomer.gold = remainingCopper / 100;
- remainingCopper %= 100;
- currentCustomer.silver = remainingCopper / 10;
- currentCustomer.copper = remainingCopper % 10;
- Debug.Log($"Purchased {item.itemName} for {item.goldCost}g {item.silverCost}s {item.copperCost}c");
- }
- private void AddItemToCustomerInventory(Item item)
- {
- if (currentCustomer == null) return;
- // Initialize lists if they're null
- if (currentCustomer.weapons == null)
- currentCustomer.weapons = new System.Collections.Generic.List<string>();
- if (currentCustomer.armor == null)
- currentCustomer.armor = new System.Collections.Generic.List<string>();
- if (currentCustomer.miscItems == null)
- currentCustomer.miscItems = new System.Collections.Generic.List<string>();
- // Add item to appropriate inventory list based on type
- switch (item.itemType)
- {
- case ItemType.Weapon:
- currentCustomer.weapons.Add(item.itemName);
- break;
- case ItemType.Armor:
- currentCustomer.armor.Add(item.itemName);
- break;
- case ItemType.Miscellaneous:
- case ItemType.Consumable:
- case ItemType.Tool:
- case ItemType.Accessory:
- currentCustomer.miscItems.Add(item.itemName);
- break;
- default:
- currentCustomer.miscItems.Add(item.itemName);
- if (Application.isEditor) Debug.LogWarning($"Unknown item type for '{item.itemName}', added to misc items");
- break;
- }
- // Trigger UI update in MainTeamSelectScript if available
- TriggerInventoryUIUpdate();
- }
- private void TriggerInventoryUIUpdate()
- {
- // The OnCharacterDataChanged event is already invoked in PurchaseItem()
- // This should trigger any listeners to update their UI
- // MainTeamSelectScript should listen to this event to refresh inventory displays
- Debug.Log("Character inventory updated - OnCharacterDataChanged event will be triggered");
- }
- private void UpdatePlayerMoney()
- {
- if (playerMoney != null && currentCustomer != null)
- {
- playerMoney.text = $"{currentCustomer.gold}g {currentCustomer.silver}s {currentCustomer.copper}c";
- }
- }
- [ContextMenu("Reload Items")]
- public void ReloadItems()
- {
- LoadAllItems();
- if (shopContainer != null && shopContainer.style.display == DisplayStyle.Flex)
- {
- RefreshItemList();
- }
- }
- // Public methods to get items by category (for compatibility with old system)
- public List<Item> GetWeapons()
- {
- return availableItems.Where(item => item.itemType == ItemType.Weapon).ToList();
- }
- public List<Item> GetArmor()
- {
- return availableItems.Where(item => item.itemType == ItemType.Armor).ToList();
- }
- public List<Item> GetMiscItems()
- {
- return availableItems.Where(item =>
- item.itemType == ItemType.Miscellaneous ||
- item.itemType == ItemType.Consumable ||
- item.itemType == ItemType.Tool ||
- item.itemType == ItemType.Accessory).ToList();
- }
- public List<Item> GetAllItems()
- {
- return new List<Item>(availableItems);
- }
- [ContextMenu("Check Shop Setup")]
- public void CheckShopSetup()
- {
- Debug.Log("=== ItemShopManager Setup Check ===");
- // Check UIDocument
- var uiDoc = GetComponent<UIDocument>();
- if (uiDoc == null)
- {
- Debug.LogError("❌ No UIDocument component found on this GameObject!");
- Debug.LogError("➤ Add a UIDocument component to fix this.");
- return;
- }
- else
- {
- Debug.Log("✓ UIDocument component found");
- }
- // Check Visual Tree Asset
- if (uiDoc.visualTreeAsset == null)
- {
- Debug.LogError("❌ UIDocument has no Visual Tree Asset assigned!");
- Debug.LogError("➤ Assign ShopUI.uxml to the UIDocument component.");
- return;
- }
- else
- {
- Debug.Log($"✓ Visual Tree Asset assigned: {uiDoc.visualTreeAsset.name}");
- }
- // Check UI elements
- var root = uiDoc.rootVisualElement;
- var container = root?.Q<VisualElement>("ShopContainer");
- if (container == null)
- {
- Debug.LogError("❌ ShopContainer element not found in the UXML!");
- Debug.LogError("➤ Make sure you're using the correct ShopUI.uxml file.");
- return;
- }
- else
- {
- Debug.Log("✓ ShopContainer element found in UXML");
- }
- // Check items
- Debug.Log($"✓ {availableItems.Count} items loaded for shop");
- Debug.Log("=== Setup Check Complete - Shop should work! ===");
- }
- [ContextMenu("Force Initialize UI")]
- public void ForceInitializeUI()
- {
- uiDocument = GetComponent<UIDocument>();
- if (uiDocument != null && uiDocument.visualTreeAsset != null)
- {
- InitializeUI();
- Debug.Log("UI forcefully initialized");
- }
- else
- {
- Debug.LogError("Cannot initialize UI - missing UIDocument or Visual Tree Asset");
- }
- }
- [ContextMenu("Debug UI State")]
- public void DebugUIState()
- {
- Debug.Log("=== UI State Debug ===");
- if (uiDocument == null)
- {
- Debug.LogError("uiDocument is null");
- return;
- }
- Debug.Log($"UIDocument sorting order: {uiDocument.sortingOrder}");
- if (uiDocument.panelSettings != null)
- {
- Debug.Log($"Panel settings sorting order: {uiDocument.panelSettings.sortingOrder}");
- }
- else
- {
- Debug.LogWarning("Panel settings is null");
- }
- var root = uiDocument.rootVisualElement;
- Debug.Log($"Root element child count: {root.childCount}");
- if (shopContainer != null)
- {
- Debug.Log($"Shop container display: {shopContainer.style.display}");
- Debug.Log($"Shop container resolved display: {shopContainer.resolvedStyle.display}");
- Debug.Log($"Shop container visible: {shopContainer.visible}");
- Debug.Log($"Shop container opacity: {shopContainer.resolvedStyle.opacity}");
- Debug.Log($"Shop container position: {shopContainer.style.position}");
- Debug.Log($"Shop container worldBound: {shopContainer.worldBound}");
- }
- else
- {
- Debug.LogError("shopContainer is null");
- }
- // Check for other UIDocuments that might be covering this one
- var allUIDocuments = FindObjectsByType<UIDocument>(FindObjectsSortMode.None);
- Debug.Log($"Found {allUIDocuments.Length} UIDocuments in scene:");
- foreach (var doc in allUIDocuments)
- {
- var panelSort = doc.panelSettings?.sortingOrder ?? -999;
- Debug.Log($" - '{doc.gameObject.name}' sortingOrder: {doc.sortingOrder}, panelSettings: {panelSort}");
- }
- }
- [ContextMenu("Force Open Shop (Test)")]
- public void ForceOpenShopTest()
- {
- // Create a test character for debugging
- var testCharacter = new TeamCharacter();
- testCharacter.name = "Test Character";
- testCharacter.gold = 100;
- testCharacter.silver = 50;
- testCharacter.copper = 25;
- Debug.Log("Opening shop with test character...");
- OpenShop(testCharacter);
- }
- void EnsurePanelSettings()
- {
- if (uiDocument.panelSettings == null || uiDocument.sortingOrder <= 2)
- {
- // Try to find and reuse existing panel settings from other UI
- var existingUI = GameObject.Find("TravelUI")?.GetComponent<UIDocument>();
- if (existingUI?.panelSettings != null)
- {
- uiDocument.panelSettings = existingUI.panelSettings;
- Debug.Log("✓ ItemShopManager: Panel Settings assigned from TravelUI");
- }
- else
- {
- // Try to find from MainTeamSelectScript or other UI components
- var mainTeamSelect = FindFirstObjectByType<MainTeamSelectScript>();
- if (mainTeamSelect != null)
- {
- var mainUIDoc = mainTeamSelect.GetComponent<UIDocument>();
- if (mainUIDoc?.panelSettings != null)
- {
- uiDocument.panelSettings = mainUIDoc.panelSettings;
- Debug.Log("✓ ItemShopManager: Panel Settings assigned from MainTeamSelectScript");
- }
- }
- }
- // Set proper sorting order (> 2 as requested)
- uiDocument.sortingOrder = 5; // Higher than 2 to ensure shop displays on top
- if (uiDocument.panelSettings != null)
- {
- // Make sure panel settings also have a high sorting order
- uiDocument.panelSettings.sortingOrder = 5;
- Debug.Log($"✓ ItemShopManager: Sorting order set to {uiDocument.sortingOrder}");
- }
- else
- {
- Debug.LogWarning("⚠ ItemShopManager: Could not assign Panel Settings. Shop may not display properly.");
- }
- }
- }
- private void OnCustomerChanged(ChangeEvent<string> evt)
- {
- // When customer is changed from dropdown, find the corresponding TeamCharacter
- string selectedName = evt.newValue;
- // Skip if no valid selection or error states
- if (string.IsNullOrEmpty(selectedName) || selectedName == "No Customer" || selectedName.StartsWith("Error"))
- {
- Debug.Log("Customer dropdown selection is invalid, skipping");
- return;
- }
- // Try to find the character from different sources depending on the scene
- TeamCharacter selectedCharacter = FindCharacterByName(selectedName);
- if (selectedCharacter != null)
- {
- currentCustomer = selectedCharacter;
- UpdatePlayerMoney();
- Debug.Log($"Customer changed to: {selectedCharacter.name}");
- }
- else
- {
- Debug.LogWarning($"Could not find character with name: {selectedName}");
- }
- }
- private void UpdateCustomerDropdown()
- {
- if (customerDropdown == null)
- {
- Debug.LogWarning("CustomerDropdown is null, cannot update");
- return;
- }
- List<string> customerOptions = new List<string>();
- try
- {
- // Check what scene we're in and populate accordingly
- if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "MainTeamSelectScene" ||
- GameObject.Find("MainTeamSelectScript") != null)
- {
- // In MainTeamSelectScene - populate with team members
- var mainTeamSelect = FindFirstObjectByType<MainTeamSelectScript>();
- if (mainTeamSelect != null)
- {
- var configuredCharacters = mainTeamSelect.GetConfiguredCharacters();
- if (configuredCharacters != null)
- {
- foreach (var character in configuredCharacters)
- {
- if (character != null && !string.IsNullOrEmpty(character.name))
- {
- customerOptions.Add(character.name);
- }
- }
- }
- }
- // If no team members found, just add the current customer
- if (customerOptions.Count == 0 && currentCustomer != null && !string.IsNullOrEmpty(currentCustomer.name))
- {
- customerOptions.Add(currentCustomer.name);
- }
- }
- else
- {
- // In TownScene or other scenes - use GameStateManager or other sources
- if (GameStateManager.Instance?.savedTeam != null)
- {
- foreach (var character in GameStateManager.Instance.savedTeam)
- {
- if (character != null && !string.IsNullOrEmpty(character.name))
- {
- customerOptions.Add(character.name);
- }
- }
- }
- // Fallback to current customer
- if (customerOptions.Count == 0 && currentCustomer != null && !string.IsNullOrEmpty(currentCustomer.name))
- {
- customerOptions.Add(currentCustomer.name);
- }
- }
- // Ensure we have at least one option
- if (customerOptions.Count == 0)
- {
- customerOptions.Add("No Customer");
- }
- // Set the dropdown options
- customerDropdown.choices = customerOptions;
- // Set the current selection safely
- if (currentCustomer != null && !string.IsNullOrEmpty(currentCustomer.name) && customerOptions.Contains(currentCustomer.name))
- {
- customerDropdown.value = currentCustomer.name;
- }
- else if (customerOptions.Count > 0)
- {
- customerDropdown.value = customerOptions[0];
- }
- Debug.Log($"Customer dropdown populated with {customerOptions.Count} customers: {string.Join(", ", customerOptions)}");
- }
- catch (System.Exception ex)
- {
- Debug.LogError($"Error updating customer dropdown: {ex.Message}");
- // Fallback to safe state
- customerDropdown.choices = new List<string> { "Error - No Customer" };
- customerDropdown.value = "Error - No Customer";
- }
- }
- private TeamCharacter FindCharacterByName(string characterName)
- {
- // Try MainTeamSelectScript first
- var mainTeamSelect = FindFirstObjectByType<MainTeamSelectScript>();
- if (mainTeamSelect != null)
- {
- var configuredCharacters = mainTeamSelect.GetConfiguredCharacters();
- foreach (var character in configuredCharacters)
- {
- if (character != null && character.name == characterName)
- {
- return character;
- }
- }
- }
- // Try GameStateManager
- if (GameStateManager.Instance?.savedTeam != null)
- {
- foreach (var character in GameStateManager.Instance.savedTeam)
- {
- if (character != null && character.name == characterName)
- {
- return character;
- }
- }
- }
- return null;
- }
- }
|