Axel Nordh 8 місяців тому
батько
коміт
c58d07ccb8
55 змінених файлів з 8552 додано та 39 видалено
  1. 51 0
      Assets/Resources/UI/MapScene/SettlementInteractionUI.uss
  2. 10 0
      Assets/Resources/UI/MapScene/SettlementInteractionUI.uxml
  3. 101 0
      Assets/Resources/UI/TownShopUI.uss
  4. 29 0
      Assets/Resources/UI/TownShopUI.uxml
  5. 342 0
      Assets/Scenes/MapScene2.unity
  6. 148 0
      Assets/Scenes/TownSceen.unity
  7. 99 0
      Assets/Scripts/Debug/SettlementCoordinateDiagnostic.cs
  8. 75 0
      Assets/Scripts/Debug/SettlementGameObjectDiagnostic.cs
  9. 80 0
      Assets/Scripts/Debug/SettlementInteractionTest.cs
  10. 108 0
      Assets/Scripts/Map/RuntimeSceneLoadTest.cs
  11. 186 0
      Assets/Scripts/Map/SceneBuildSettingsChecker.cs
  12. 148 0
      Assets/Scripts/Map/SettlementDetectionHotfix.cs
  13. 250 0
      Assets/Scripts/Map/SettlementInteractionCompleteFix.cs
  14. 254 0
      Assets/Scripts/Map/SettlementInteractionDebugger.cs
  15. 222 0
      Assets/Scripts/Map/SettlementInteractionFixer.cs
  16. 409 0
      Assets/Scripts/Map/SettlementInteractionManager.cs
  17. 12 0
      Assets/Scripts/Map/SimpleTeamPlacement.cs
  18. 10 0
      Assets/Scripts/MapMaker2/Data/MapData.cs
  19. 228 0
      Assets/Scripts/Town/ItemCreatorHelper.cs
  20. 150 0
      Assets/Scripts/Town/SettlementContext.cs
  21. 131 0
      Assets/Scripts/Town/SettlementTestHelper.cs
  22. 45 0
      Assets/Scripts/Town/ShopData.cs
  23. 103 0
      Assets/Scripts/Town/ShopNameGenerator.cs
  24. 131 0
      Assets/Scripts/Town/SimpleTownShopUI.cs
  25. 44 0
      Assets/Scripts/Town/TestTownShopUI.cs
  26. 94 0
      Assets/Scripts/Town/TownBuilding.cs
  27. 235 5
      Assets/Scripts/Town/TownManager.cs
  28. 275 0
      Assets/Scripts/Town/TownSetupHelper.cs
  29. 271 0
      Assets/Scripts/Town/TownShop.cs
  30. 1045 0
      Assets/Scripts/Town/TownShopManager.cs
  31. 778 0
      Assets/Scripts/Town/TownShopUI.cs
  32. 84 0
      Assets/Scripts/Town/TownShopUIDebugger.cs
  33. 0 0
      Assets/Scripts/Town/TownShopUI_Clean.cs
  34. 0 0
      Assets/Scripts/Town/TownShopUI_Fixed.cs
  35. 204 0
      Assets/Scripts/UI/SettlementInteractionUI.cs
  36. 88 0
      Assets/Scripts/UI/SettlementUIBridge.cs
  37. 101 0
      Assets/UI/TownShopUI.uss
  38. 38 0
      Assets/UI/TownShopUI.uxml
  39. 272 0
      Assets/UI/TownUI.uss
  40. 129 0
      Assets/UI/TownUI.uxml
  41. 272 0
      Assets/UI/TownUI_New.uss
  42. 58 0
      DEBUG_SETTLEMENT_INTERACTION.md
  43. 89 0
      ERROR_FIXES_SUMMARY.md
  44. 195 0
      MAP_SETTLEMENT_INTERACTION_GUIDE.md
  45. 131 0
      MEDIEVAL_TOWN_SETUP_GUIDE.md
  46. 3 0
      ProjectSettings/EditorBuildSettings.asset
  47. 68 0
      SETTLEMENT_INTERACTION_OPTIMAL_SETUP.md
  48. 119 0
      SETTLEMENT_INTERACTION_TROUBLESHOOTING.md
  49. 53 0
      SETTLEMENT_UI_BRIDGE_FIX.md
  50. 57 0
      SHOP_UI_FIX_GUIDE.md
  51. 111 0
      TOWNSHOPUI_FIX_SUMMARY.md
  52. 138 0
      TOWN_QUICK_SETUP.md
  53. 244 0
      TOWN_SYSTEM_GUIDE.md
  54. 3 3
      UserSettings/EditorUserSettings.asset
  55. 31 31
      UserSettings/Layouts/default-6000.dwlt

+ 51 - 0
Assets/Resources/UI/MapScene/SettlementInteractionUI.uss

@@ -0,0 +1,51 @@
+/* Settlement Interaction UI Styles */
+
+.settlement-prompt {
+    position: absolute;
+    top: 20px;
+    left: 50%;
+    translate: -50% 0;
+    background-color: rgba(0, 0, 0, 0.8);
+    border-radius: 10px;
+    padding: 15px;
+    border-width: 2px;
+    border-color: rgb(255, 215, 0);
+    min-width: 300px;
+    align-items: center;
+    justify-content: center;
+}
+
+.prompt-container {
+    align-items: center;
+    justify-content: center;
+}
+
+.settlement-name {
+    font-size: 18px;
+    color: rgb(255, 215, 0);
+    font-weight: bold;
+    margin-bottom: 5px;
+    text-align: center;
+    -unity-text-align: middle-center;
+}
+
+.interaction-instruction {
+    font-size: 14px;
+    color: rgb(255, 255, 255);
+    text-align: center;
+    -unity-text-align: middle-center;
+    margin-top: 5px;
+}
+
+/* Animation for the prompt */
+.settlement-prompt {
+    transition-property: opacity;
+    transition-duration: 0.3s;
+    transition-timing-function: ease-in-out;
+}
+
+/* Hover effect for better visibility */
+.settlement-prompt:hover {
+    background-color: rgba(0, 0, 0, 0.9);
+    border-color: rgb(255, 255, 0);
+}

+ 10 - 0
Assets/Resources/UI/MapScene/SettlementInteractionUI.uxml

@@ -0,0 +1,10 @@
+<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
+    <Style src="project://database/Assets/Resources/UI/MapScene/SettlementInteractionUI.uss?fileID=7433441132597879392&amp;guid=YOUR_USS_GUID&amp;type=3#SettlementInteractionUI" />
+    
+    <ui:VisualElement name="SettlementPrompt" class="settlement-prompt">
+        <ui:VisualElement class="prompt-container">
+            <ui:Label name="SettlementName" text="Settlement Name" class="settlement-name" />
+            <ui:Label name="InteractionInstruction" text="Press E to enter Town" class="interaction-instruction" />
+        </ui:VisualElement>
+    </ui:VisualElement>
+</ui:UXML>

+ 101 - 0
Assets/Resources/UI/TownShopUI.uss

@@ -0,0 +1,101 @@
+/* Shop Item Styles */
+.shop-item {
+    flex-direction: row;
+    align-items: center;
+    justify-content: space-between;
+    padding: 10px;
+    margin-bottom: 5px;
+    background-color: rgb(250, 250, 250);
+    border-width: 1px;
+    border-color: rgb(200, 200, 200);
+    border-radius: 5px;
+}
+
+.shop-item:hover {
+    background-color: rgb(240, 240, 240);
+}
+
+.sell-item {
+    flex-direction: row;
+    align-items: center;
+    justify-content: space-between;
+    padding: 10px;
+    margin-bottom: 5px;
+    background-color: rgb(250, 245, 240);
+    border-width: 1px;
+    border-color: rgb(200, 180, 160);
+    border-radius: 5px;
+}
+
+.sell-item:hover {
+    background-color: rgb(240, 235, 230);
+}
+
+.item-name {
+    font-size: 16px;
+    color: rgb(50, 50, 50);
+    font-weight: bold;
+    flex-shrink: 0;
+    width: 200px;
+}
+
+.item-description {
+    font-size: 12px;
+    color: rgb(100, 100, 100);
+    flex-grow: 1;
+    margin-left: 10px;
+    margin-right: 10px;
+}
+
+.item-price {
+    font-size: 14px;
+    color: rgb(0, 120, 0);
+    font-weight: bold;
+    flex-shrink: 0;
+    width: 100px;
+    text-align: center;
+}
+
+.buy-button {
+    background-color: rgb(50, 150, 50);
+    color: rgb(255, 255, 255);
+    border-width: 0;
+    border-radius: 3px;
+    padding: 5px 15px;
+    font-weight: bold;
+}
+
+.buy-button:hover {
+    background-color: rgb(40, 130, 40);
+}
+
+.sell-button {
+    background-color: rgb(150, 100, 50);
+    color: rgb(255, 255, 255);
+    border-width: 0;
+    border-radius: 3px;
+    padding: 5px 15px;
+    font-weight: bold;
+}
+
+.sell-button:hover {
+    background-color: rgb(130, 80, 30);
+}
+
+.unaffordable {
+    color: rgb(150, 50, 50) !important;
+}
+
+.not-accepted {
+    color: rgb(150, 50, 50) !important;
+}
+
+.active-tab {
+    background-color: rgb(200, 180, 140) !important;
+    color: rgb(50, 50, 50) !important;
+}
+
+/* Medieval styling for the shop window */
+#shop-window {
+    background-image: url('project://database/Assets/UI/medieval-background.png');
+}

+ 29 - 0
Assets/Resources/UI/TownShopUI.uxml

@@ -0,0 +1,29 @@
+<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
+    <Style src="project://database/Assets/Resources/UI/TownShopUI.uss?fileID=7433441132597879392&amp;guid=0eb65119c75038e47ba7e4ac2def995d&amp;type=3#TownShopUI" />
+    <ui:VisualElement name="shop-container" style="position: absolute; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.8); justify-content: center; align-items: center; display: none;">
+        <ui:VisualElement name="shop-window" style="width: 800px; height: 600px; background-color: rgb(240, 220, 180); border-left-color: rgb(139, 69, 19); border-right-color: rgb(139, 69, 19); border-top-color: rgb(139, 69, 19); border-bottom-color: rgb(139, 69, 19); border-left-width: 3px; border-right-width: 3px; border-top-width: 3px; border-bottom-width: 3px; border-top-left-radius: 10px; border-bottom-left-radius: 10px; border-top-right-radius: 10px; border-bottom-right-radius: 10px; padding-left: 20px; padding-right: 20px; padding-top: 20px; padding-bottom: 20px;">
+            <ui:VisualElement name="shop-header" style="flex-direction: row; justify-content: space-between; align-items: center; margin-bottom: 15px; height: 40px;">
+                <ui:VisualElement style="flex-direction: column;">
+                    <ui:Label name="shop-name" text="General Store" style="font-size: 24px; color: rgb(139, 69, 19); -unity-font-style: bold;" />
+                    <ui:Label name="shopkeeper-name" text="Shopkeeper: Merchant" style="font-size: 14px; color: rgb(80, 40, 10); font-style: italic;" />
+                </ui:VisualElement>
+                <ui:Button name="close-button" text="✕" style="width: 30px; height: 30px; background-color: rgb(200, 50, 50); color: rgb(255, 255, 255); border-width: 0; border-top-left-radius: 15px; border-bottom-left-radius: 15px; border-top-right-radius: 15px; border-bottom-right-radius: 15px; font-size: 16px; -unity-font-style: bold;" />
+            </ui:VisualElement>
+            <ui:VisualElement name="customer-panel" style="flex-direction: row; justify-content: space-between; align-items: center; margin-bottom: 15px; background-color: rgb(220, 200, 160); padding-left: 10px; padding-right: 10px; padding-top: 10px; padding-bottom: 10px; border-top-left-radius: 5px; border-bottom-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px;">
+                <ui:DropdownField name="customer-dropdown" label="Customer:" style="width: 200px;" />
+                <ui:Label name="money-label" text="Money: 100g 50s 25c" style="color: rgb(0, 120, 0); -unity-font-style: bold;" />
+            </ui:VisualElement>
+            <ui:VisualElement name="tab-container" style="flex-direction: row; margin-bottom: 15px; height: 35px;">
+                <ui:Button name="buy-tab" text="Buy" class="active-tab" style="flex-grow: 1; margin-right: 5px; background-color: rgb(200, 180, 140); border-width: 1px; border-color: rgb(139, 69, 19); border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-left-radius: 0; border-bottom-right-radius: 0;" />
+                <ui:Button name="sell-tab" text="Sell" style="flex-grow: 1; margin-left: 5px; background-color: rgb(180, 160, 120); border-width: 1px; border-color: rgb(139, 69, 19); border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-left-radius: 0; border-bottom-right-radius: 0;" />
+            </ui:VisualElement>
+            <ui:VisualElement name="filters" style="flex-direction: row; margin-bottom: 15px; align-items: center;">
+                <ui:TextField name="search-field" label="Search:" placeholder-text="Enter item name..." style="flex-grow: 1; margin-right: 10px;" />
+                <ui:DropdownField name="category-filter" label="Category:" style="width: 150px;" />
+            </ui:VisualElement>
+            <ui:ScrollView name="item-list" style="flex-grow: 1; min-height: 200px; background-color: rgb(255, 255, 255); border-width: 1px; border-color: rgb(139, 69, 19); border-top-left-radius: 5px; border-bottom-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; padding-left: 10px; padding-right: 10px; padding-top: 10px; padding-bottom: 10px;">
+                <ui:Label text="Items will appear here..." style="color: rgb(150, 150, 150); font-style: italic; -unity-text-align: middle-center; margin-top: 50px;" />
+            </ui:ScrollView>
+        </ui:VisualElement>
+    </ui:VisualElement>
+</ui:UXML>

+ 342 - 0
Assets/Scenes/MapScene2.unity

@@ -204,6 +204,50 @@ Transform:
   m_Children: []
   m_Father: {fileID: 0}
   m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
+--- !u!1 &442394812
+GameObject:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  serializedVersion: 6
+  m_Component:
+  - component: {fileID: 442394814}
+  - component: {fileID: 442394813}
+  m_Layer: 0
+  m_Name: SettlementCoordinateDiagnostic
+  m_TagString: Untagged
+  m_Icon: {fileID: 0}
+  m_NavMeshLayer: 0
+  m_StaticEditorFlags: 0
+  m_IsActive: 1
+--- !u!114 &442394813
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 442394812}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 11500000, guid: 318e63380eb7ced4b998333bb8fe3f02, type: 3}
+  m_Name: 
+  m_EditorClassIdentifier: 
+--- !u!4 &442394814
+Transform:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 442394812}
+  serializedVersion: 2
+  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
+  m_LocalPosition: {x: 50.538914, y: 35.312664, z: 66.63946}
+  m_LocalScale: {x: 1, y: 1, z: 1}
+  m_ConstrainProportionsScale: 0
+  m_Children: []
+  m_Father: {fileID: 0}
+  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
 --- !u!1 &591284416
 GameObject:
   m_ObjectHideFlags: 0
@@ -356,6 +400,75 @@ MonoBehaviour:
   eventMarkerColor: {r: 1, g: 0, b: 0, a: 1}
   maxActiveMarkers: 5
   showSetupLogs: 0
+--- !u!1 &711527291
+GameObject:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  serializedVersion: 6
+  m_Component:
+  - component: {fileID: 711527293}
+  - component: {fileID: 711527292}
+  - component: {fileID: 711527297}
+  m_Layer: 0
+  m_Name: SettlementIntegrationManager
+  m_TagString: Untagged
+  m_Icon: {fileID: 0}
+  m_NavMeshLayer: 0
+  m_StaticEditorFlags: 0
+  m_IsActive: 1
+--- !u!114 &711527292
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 711527291}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 11500000, guid: f95de9742abd3b345a5027d0b6a67fd1, type: 3}
+  m_Name: 
+  m_EditorClassIdentifier: 
+  teamMarker: {fileID: 0}
+  interactionDistance: 2
+  enterSettlementKey: 101
+  autoEnterOnStop: 1
+  autoEnterDelay: 1
+  interactionPrompt: {fileID: 2053130503}
+  townSceneName: TownSceen
+  enableDebugLogs: 1
+  exitCooldown: 3
+--- !u!4 &711527293
+Transform:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 711527291}
+  serializedVersion: 2
+  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
+  m_LocalPosition: {x: 0, y: 0, z: 0}
+  m_LocalScale: {x: 1, y: 1, z: 1}
+  m_ConstrainProportionsScale: 0
+  m_Children: []
+  m_Father: {fileID: 0}
+  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
+--- !u!114 &711527297
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 711527291}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 11500000, guid: 5e4958ad5215db74397a0e4a4c6ed78f, type: 3}
+  m_Name: 
+  m_EditorClassIdentifier: 
+  enableFix: 1
+  forceUIUpdates: 1
+  verboseDebug: 1
 --- !u!1 &731368432
 GameObject:
   m_ObjectHideFlags: 0
@@ -406,6 +519,102 @@ Transform:
   m_Children: []
   m_Father: {fileID: 0}
   m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
+--- !u!1 &1064064992
+GameObject:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  serializedVersion: 6
+  m_Component:
+  - component: {fileID: 1064064994}
+  - component: {fileID: 1064064993}
+  m_Layer: 0
+  m_Name: SettlementInteractionTest
+  m_TagString: Untagged
+  m_Icon: {fileID: 0}
+  m_NavMeshLayer: 0
+  m_StaticEditorFlags: 0
+  m_IsActive: 1
+--- !u!114 &1064064993
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 1064064992}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 11500000, guid: 00a549e6bc5d0e940bd6ca3342f41135, type: 3}
+  m_Name: 
+  m_EditorClassIdentifier: 
+--- !u!4 &1064064994
+Transform:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 1064064992}
+  serializedVersion: 2
+  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
+  m_LocalPosition: {x: 50.538914, y: 35.312664, z: 66.63946}
+  m_LocalScale: {x: 1, y: 1, z: 1}
+  m_ConstrainProportionsScale: 0
+  m_Children: []
+  m_Father: {fileID: 0}
+  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
+--- !u!1 &1079165143
+GameObject:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  serializedVersion: 6
+  m_Component:
+  - component: {fileID: 1079165145}
+  - component: {fileID: 1079165144}
+  m_Layer: 0
+  m_Name: SettlementContext
+  m_TagString: Untagged
+  m_Icon: {fileID: 0}
+  m_NavMeshLayer: 0
+  m_StaticEditorFlags: 0
+  m_IsActive: 1
+--- !u!114 &1079165144
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 1079165143}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 11500000, guid: e8529f25fd07e1d4cba4c01b71b290a1, type: 3}
+  m_Name: 
+  m_EditorClassIdentifier: 
+  settlementName: Haven Village
+  settlementType: 0
+  hasHarbor: 0
+  mapPosition: {x: 0, y: 0}
+  settlementSeed: 0
+  availableShops: []
+  generatedShopData: []
+  isGenerated: 0
+--- !u!4 &1079165145
+Transform:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 1079165143}
+  serializedVersion: 2
+  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
+  m_LocalPosition: {x: 0, y: 0, z: 0}
+  m_LocalScale: {x: 1, y: 1, z: 1}
+  m_ConstrainProportionsScale: 0
+  m_Children: []
+  m_Father: {fileID: 0}
+  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
 --- !u!1 &1243674619
 GameObject:
   m_ObjectHideFlags: 0
@@ -901,6 +1110,50 @@ MonoBehaviour:
   pulseSpeed: 2
   pulseIntensity: 0.3
   showDebugInfo: 0
+--- !u!1 &1613003761
+GameObject:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  serializedVersion: 6
+  m_Component:
+  - component: {fileID: 1613003763}
+  - component: {fileID: 1613003762}
+  m_Layer: 0
+  m_Name: SettlementDebugger
+  m_TagString: Untagged
+  m_Icon: {fileID: 0}
+  m_NavMeshLayer: 0
+  m_StaticEditorFlags: 0
+  m_IsActive: 1
+--- !u!114 &1613003762
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 1613003761}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 11500000, guid: eea58f1a8dd1de1479f058ed1ecf8001, type: 3}
+  m_Name: 
+  m_EditorClassIdentifier: 
+--- !u!4 &1613003763
+Transform:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 1613003761}
+  serializedVersion: 2
+  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
+  m_LocalPosition: {x: 50.538914, y: 35.312664, z: 66.63946}
+  m_LocalScale: {x: 1, y: 1, z: 1}
+  m_ConstrainProportionsScale: 0
+  m_Children: []
+  m_Father: {fileID: 0}
+  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
 --- !u!1 &1953346056
 GameObject:
   m_ObjectHideFlags: 0
@@ -1060,6 +1313,89 @@ MonoBehaviour:
     m_MipBias: 0
     m_VarianceClampScale: 0.9
     m_ContrastAdaptiveSharpening: 0
+--- !u!1 &2053130503
+GameObject:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  serializedVersion: 6
+  m_Component:
+  - component: {fileID: 2053130505}
+  - component: {fileID: 2053130507}
+  - component: {fileID: 2053130504}
+  - component: {fileID: 2053130506}
+  m_Layer: 0
+  m_Name: SettlementInteractionUI
+  m_TagString: Untagged
+  m_Icon: {fileID: 0}
+  m_NavMeshLayer: 0
+  m_StaticEditorFlags: 0
+  m_IsActive: 1
+--- !u!114 &2053130504
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 2053130503}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 19102, guid: 0000000000000000e000000000000000, type: 0}
+  m_Name: 
+  m_EditorClassIdentifier: 
+  m_PanelSettings: {fileID: 11400000, guid: 0d7125098b341c74d868b72a1bacddf4, type: 2}
+  m_ParentUI: {fileID: 0}
+  sourceAsset: {fileID: 9197481963319205126, guid: 4869828293b058740982d04abc424e57, type: 3}
+  m_SortingOrder: 0
+  m_WorldSpaceSizeMode: 1
+  m_WorldSpaceWidth: 1920
+  m_WorldSpaceHeight: 1080
+--- !u!4 &2053130505
+Transform:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 2053130503}
+  serializedVersion: 2
+  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
+  m_LocalPosition: {x: 0, y: 0, z: 0}
+  m_LocalScale: {x: 1, y: 1, z: 1}
+  m_ConstrainProportionsScale: 0
+  m_Children: []
+  m_Father: {fileID: 0}
+  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
+--- !u!114 &2053130506
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 2053130503}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 11500000, guid: 35493be37a24d624398001575c821f40, type: 3}
+  m_Name: 
+  m_EditorClassIdentifier: 
+  settlementUI: {fileID: 0}
+  controlUIVisibility: 1
+--- !u!114 &2053130507
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 2053130503}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 11500000, guid: e239a6776f8a6514b9cfdee153af3967, type: 3}
+  m_Name: 
+  m_EditorClassIdentifier: 
+  uiDocument: {fileID: 2053130504}
+  promptContainerName: SettlementPrompt
+  settlementNameLabelName: SettlementName
+  instructionLabelName: InteractionInstruction
 --- !u!1660057539 &9223372036854775807
 SceneRoots:
   m_ObjectHideFlags: 0
@@ -1075,3 +1411,9 @@ SceneRoots:
   - {fileID: 684362519}
   - {fileID: 731368434}
   - {fileID: 1312298684}
+  - {fileID: 711527293}
+  - {fileID: 2053130505}
+  - {fileID: 1613003763}
+  - {fileID: 1079165145}
+  - {fileID: 442394814}
+  - {fileID: 1064064994}

+ 148 - 0
Assets/Scenes/TownSceen.unity

@@ -119,6 +119,76 @@ NavMeshSettings:
     debug:
       m_Flags: 0
   m_NavMeshData: {fileID: 0}
+--- !u!1 &99766904
+GameObject:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  serializedVersion: 6
+  m_Component:
+  - component: {fileID: 99766908}
+  - component: {fileID: 99766907}
+  - component: {fileID: 99766906}
+  m_Layer: 0
+  m_Name: TownManager
+  m_TagString: Untagged
+  m_Icon: {fileID: 0}
+  m_NavMeshLayer: 0
+  m_StaticEditorFlags: 0
+  m_IsActive: 1
+--- !u!114 &99766906
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 99766904}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 19102, guid: 0000000000000000e000000000000000, type: 0}
+  m_Name: 
+  m_EditorClassIdentifier: 
+  m_PanelSettings: {fileID: 11400000, guid: 0d7125098b341c74d868b72a1bacddf4, type: 2}
+  m_ParentUI: {fileID: 0}
+  sourceAsset: {fileID: 9197481963319205126, guid: 967d65d29dca2264eacf769028feb446, type: 3}
+  m_SortingOrder: 0
+  m_WorldSpaceSizeMode: 1
+  m_WorldSpaceWidth: 1920
+  m_WorldSpaceHeight: 1080
+--- !u!114 &99766907
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 99766904}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 11500000, guid: 20ec35c61c7067b4b9e0a4f4d6dfe560, type: 3}
+  m_Name: 
+  m_EditorClassIdentifier: 
+  townName: Test Village 2
+  hasHarbor: 0
+  townUI: {fileID: 99766906}
+  townCamera: {fileID: 712987408}
+  shopManager: {fileID: 0}
+  currentTeam: []
+--- !u!4 &99766908
+Transform:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 99766904}
+  serializedVersion: 2
+  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
+  m_LocalPosition: {x: 0, y: 0, z: 0}
+  m_LocalScale: {x: 1, y: 1, z: 1}
+  m_ConstrainProportionsScale: 0
+  m_Children: []
+  m_Father: {fileID: 0}
+  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
 --- !u!1 &276547329
 GameObject:
   m_ObjectHideFlags: 0
@@ -129,6 +199,7 @@ GameObject:
   m_Component:
   - component: {fileID: 276547331}
   - component: {fileID: 276547330}
+  - component: {fileID: 276547332}
   m_Layer: 0
   m_Name: Directional Light
   m_TagString: Untagged
@@ -216,6 +287,29 @@ Transform:
   m_Children: []
   m_Father: {fileID: 0}
   m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0}
+--- !u!114 &276547332
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 276547329}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 11500000, guid: 474bcb49853aa07438625e644c072ee6, type: 3}
+  m_Name: 
+  m_EditorClassIdentifier: 
+  m_Version: 3
+  m_UsePipelineSettings: 1
+  m_AdditionalLightsShadowResolutionTier: 2
+  m_LightLayerMask: 1
+  m_RenderingLayers: 1
+  m_CustomShadowLayers: 0
+  m_ShadowLayerMask: 1
+  m_ShadowRenderingLayers: 1
+  m_LightCookieSize: {x: 1, y: 1}
+  m_LightCookieOffset: {x: 0, y: 0}
+  m_SoftShadowQuality: 0
 --- !u!1 &712987406
 GameObject:
   m_ObjectHideFlags: 0
@@ -308,9 +402,63 @@ Transform:
   m_Children: []
   m_Father: {fileID: 0}
   m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
+--- !u!1 &1925990311
+GameObject:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  serializedVersion: 6
+  m_Component:
+  - component: {fileID: 1925990313}
+  - component: {fileID: 1925990312}
+  m_Layer: 0
+  m_Name: SettlementContext
+  m_TagString: Untagged
+  m_Icon: {fileID: 0}
+  m_NavMeshLayer: 0
+  m_StaticEditorFlags: 0
+  m_IsActive: 1
+--- !u!114 &1925990312
+MonoBehaviour:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 1925990311}
+  m_Enabled: 1
+  m_EditorHideFlags: 0
+  m_Script: {fileID: 11500000, guid: e8529f25fd07e1d4cba4c01b71b290a1, type: 3}
+  m_Name: 
+  m_EditorClassIdentifier: 
+  settlementName: Test Village
+  settlementType: 1
+  hasHarbor: 0
+  mapPosition: {x: 50, y: 50}
+  settlementSeed: -485847120
+  availableShops: []
+  generatedShopData: []
+  isGenerated: 1
+--- !u!4 &1925990313
+Transform:
+  m_ObjectHideFlags: 0
+  m_CorrespondingSourceObject: {fileID: 0}
+  m_PrefabInstance: {fileID: 0}
+  m_PrefabAsset: {fileID: 0}
+  m_GameObject: {fileID: 1925990311}
+  serializedVersion: 2
+  m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
+  m_LocalPosition: {x: 0, y: 0, z: 0}
+  m_LocalScale: {x: 1, y: 1, z: 1}
+  m_ConstrainProportionsScale: 0
+  m_Children: []
+  m_Father: {fileID: 0}
+  m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
 --- !u!1660057539 &9223372036854775807
 SceneRoots:
   m_ObjectHideFlags: 0
   m_Roots:
   - {fileID: 712987409}
   - {fileID: 276547331}
+  - {fileID: 99766908}
+  - {fileID: 1925990313}

+ 99 - 0
Assets/Scripts/Debug/SettlementCoordinateDiagnostic.cs

@@ -0,0 +1,99 @@
+using UnityEngine;
+
+/// <summary>
+/// Enhanced diagnostic script specifically for debugging settlement coordinate issues
+/// </summary>
+public class SettlementCoordinateDiagnostic : MonoBehaviour
+{
+    [ContextMenu("Debug Settlement Coordinates")]
+    public void DebugSettlementCoordinates()
+    {
+        Debug.Log("=== SETTLEMENT COORDINATE DIAGNOSTIC ===");
+
+        var settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
+        var teamMarker = GameObject.Find("TeamMarker");
+        var mapMaker = FindFirstObjectByType<MapMaker2>();
+
+        if (settlementManager == null || teamMarker == null || mapMaker == null)
+        {
+            Debug.LogError("❌ Missing components for coordinate diagnostic");
+            return;
+        }
+
+        var mapData = mapMaker.GetMapData();
+        if (mapData == null)
+        {
+            Debug.LogError("❌ MapData is null");
+            return;
+        }
+
+        // Get current team position
+        Vector3 worldPos = teamMarker.transform.position;
+        Vector2 teamWorldPos = new Vector2(worldPos.x, worldPos.z);
+        Debug.Log($"🎯 TeamMarker World Position: {worldPos}");
+        Debug.Log($"🎯 TeamMarker 2D Position: {teamWorldPos}");
+
+        // Test coordinate conversion (replicate SettlementInteractionManager logic)
+        Debug.Log("\n🔍 COORDINATE CONVERSION TEST:");
+
+        // Get tile size from MapVisualizer
+        float tileSize = 1f;
+        var mapVisualizer = FindFirstObjectByType<MapVisualizer>();
+        if (mapVisualizer != null && mapVisualizer.tileSize > 0)
+        {
+            tileSize = mapVisualizer.tileSize;
+            Debug.Log($"   MapVisualizer tileSize: {tileSize}");
+        }
+        else
+        {
+            Debug.Log($"   Using default tileSize: {tileSize}");
+        }
+
+        // Convert world to map coordinates (same as SettlementInteractionManager)
+        Vector2Int mapPos = new Vector2Int(
+            Mathf.RoundToInt(teamWorldPos.x / tileSize),
+            Mathf.RoundToInt(teamWorldPos.y / tileSize)
+        );
+        Debug.Log($"   Converted Map Position: {mapPos}");
+
+        // Check settlements near this position
+        Debug.Log("\n🏛️ SETTLEMENT PROXIMITY CHECK:");
+        var allSettlements = mapData.GetAllSettlements();
+        Debug.Log($"   Total settlements: {allSettlements.Count}");
+
+        int foundNearby = 0;
+        float interactionDistance = 2f; // Default from SettlementInteractionManager
+
+        foreach (var settlement in allSettlements)
+        {
+            float distance = Vector2Int.Distance(mapPos, settlement.position);
+            if (distance <= 5f) // Show all within 5 tiles for debugging
+            {
+                string status = distance <= interactionDistance ? "✅ WITHIN RANGE" : "❌ TOO FAR";
+                Debug.Log($"   Settlement '{settlement.name}' at {settlement.position}, distance: {distance:F1} {status}");
+
+                if (distance <= interactionDistance)
+                {
+                    foundNearby++;
+                }
+            }
+        }
+
+        Debug.Log($"   Settlements within interaction distance ({interactionDistance}): {foundNearby}");
+
+        // Test MapData.GetSettlementAt method
+        Debug.Log("\n🔍 MAPDATA.GETSETTLEMENTAT TEST:");
+        var foundSettlement = mapData.GetSettlementAt(mapPos, interactionDistance);
+        Debug.Log($"   MapData.GetSettlementAt({mapPos}, {interactionDistance}): {(foundSettlement != null ? foundSettlement.name : "NULL")}");
+
+        // Manual verification - check exact position
+        Debug.Log("\n🎯 EXACT POSITION CHECK:");
+        foreach (var settlement in allSettlements)
+        {
+            if (settlement.position == mapPos)
+            {
+                Debug.Log($"   ✅ EXACT MATCH: Settlement '{settlement.name}' at exactly {settlement.position}");
+            }
+        }
+    }
+}

+ 75 - 0
Assets/Scripts/Debug/SettlementGameObjectDiagnostic.cs

@@ -0,0 +1,75 @@
+using UnityEngine;
+
+/// <summary>
+/// Detailed diagnostic script to check what components are actually on GameObjects
+/// </summary>
+public class SettlementGameObjectDiagnostic : MonoBehaviour
+{
+    [ContextMenu("Diagnose Settlement GameObjects")]
+    public void DiagnoseGameObjects()
+    {
+        Debug.Log("=== SETTLEMENT GAMEOBJECT DIAGNOSTIC ===");
+
+        // Find all GameObjects with settlement-related names
+        var allObjects = FindObjectsOfType<GameObject>();
+
+        foreach (var obj in allObjects)
+        {
+            if (obj.name.Contains("Settlement") || obj.name.Contains("settlement"))
+            {
+                Debug.Log($"\n🎯 GameObject: '{obj.name}'");
+                Debug.Log($"   Active: {obj.activeInHierarchy}");
+                Debug.Log($"   Tag: {obj.tag}");
+
+                // List all components
+                var components = obj.GetComponents<Component>();
+                Debug.Log($"   Components ({components.Length}):");
+                foreach (var comp in components)
+                {
+                    if (comp != null)
+                    {
+                        Debug.Log($"     - {comp.GetType().Name}");
+                    }
+                }
+            }
+        }
+
+        Debug.Log("\n=== SPECIFIC COMPONENT SEARCH ===");
+
+        // Search for specific components
+        var settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
+        var settlementUI = FindFirstObjectByType<SettlementInteractionUI>();
+        var settlementBridge = FindFirstObjectByType<SettlementUIBridge>();
+
+        Debug.Log($"SettlementInteractionManager found: {settlementManager != null}");
+        if (settlementManager != null)
+        {
+            Debug.Log($"   On GameObject: '{settlementManager.gameObject.name}'");
+        }
+
+        Debug.Log($"SettlementInteractionUI found: {settlementUI != null}");
+        if (settlementUI != null)
+        {
+            Debug.Log($"   On GameObject: '{settlementUI.gameObject.name}'");
+        }
+
+        Debug.Log($"SettlementUIBridge found: {settlementBridge != null}");
+        if (settlementBridge != null)
+        {
+            Debug.Log($"   On GameObject: '{settlementBridge.gameObject.name}'");
+            Debug.Log($"   Settlement UI Reference: {settlementBridge.settlementUI != null}");
+        }
+
+        Debug.Log("\n=== UI DOCUMENT SEARCH ===");
+
+        // Check for UIDocument components
+        var uiDocuments = FindObjectsOfType<UnityEngine.UIElements.UIDocument>();
+        Debug.Log($"Found {uiDocuments.Length} UIDocument components:");
+
+        foreach (var uiDoc in uiDocuments)
+        {
+            Debug.Log($"   UIDocument on '{uiDoc.gameObject.name}'");
+            Debug.Log($"     Asset: {(uiDoc.visualTreeAsset != null ? uiDoc.visualTreeAsset.name : "NULL")}");
+        }
+    }
+}

+ 80 - 0
Assets/Scripts/Debug/SettlementInteractionTest.cs

@@ -0,0 +1,80 @@
+using UnityEngine;
+
+/// <summary>
+/// Force test the SettlementInteractionManager detection logic
+/// </summary>
+public class SettlementInteractionTest : MonoBehaviour
+{
+    [ContextMenu("Force Test Settlement Detection")]
+    public void ForceTestSettlementDetection()
+    {
+        Debug.Log("=== FORCING SETTLEMENT INTERACTION MANAGER TEST ===");
+
+        var settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
+        if (settlementManager == null)
+        {
+            Debug.LogError("❌ SettlementInteractionManager not found");
+            return;
+        }
+
+        Debug.Log("✅ SettlementInteractionManager found");
+        Debug.Log($"   GameObject: {settlementManager.gameObject.name}");
+        Debug.Log($"   Enabled: {settlementManager.enabled}");
+        Debug.Log($"   GameObject Active: {settlementManager.gameObject.activeInHierarchy}");
+
+        // Get private fields using reflection to see current state
+        var teamMarkerField = typeof(SettlementInteractionManager).GetField("teamMarker",
+            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
+        var mapDataField = typeof(SettlementInteractionManager).GetField("mapData",
+            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
+        var currentNearbySettlementField = typeof(SettlementInteractionManager).GetField("currentNearbySettlement",
+            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
+
+        if (teamMarkerField != null)
+        {
+            var teamMarker = teamMarkerField.GetValue(settlementManager) as Transform;
+            Debug.Log($"   TeamMarker reference: {(teamMarker != null ? teamMarker.name : "NULL")}");
+        }
+
+        if (mapDataField != null)
+        {
+            var mapData = mapDataField.GetValue(settlementManager);
+            Debug.Log($"   MapData reference: {(mapData != null ? "EXISTS" : "NULL")}");
+        }
+
+        if (currentNearbySettlementField != null)
+        {
+            var currentSettlement = currentNearbySettlementField.GetValue(settlementManager);
+            Debug.Log($"   Current nearby settlement: {(currentSettlement != null ? "EXISTS" : "NULL")}");
+        }
+
+        // Force call the CheckForSettlementInteraction method using reflection
+        Debug.Log("\n🔍 FORCING CheckForSettlementInteraction()...");
+        var checkMethod = typeof(SettlementInteractionManager).GetMethod("CheckForSettlementInteraction",
+            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
+
+        if (checkMethod != null)
+        {
+            try
+            {
+                checkMethod.Invoke(settlementManager, null);
+                Debug.Log("✅ CheckForSettlementInteraction() called successfully");
+            }
+            catch (System.Exception e)
+            {
+                Debug.LogError($"❌ Error calling CheckForSettlementInteraction(): {e.Message}");
+            }
+        }
+        else
+        {
+            Debug.LogError("❌ CheckForSettlementInteraction method not found");
+        }
+
+        // Check state after forced call
+        if (currentNearbySettlementField != null)
+        {
+            var currentSettlement = currentNearbySettlementField.GetValue(settlementManager);
+            Debug.Log($"   Current nearby settlement AFTER: {(currentSettlement != null ? "EXISTS" : "NULL")}");
+        }
+    }
+}

+ 108 - 0
Assets/Scripts/Map/RuntimeSceneLoadTest.cs

@@ -0,0 +1,108 @@
+using UnityEngine;
+using UnityEngine.SceneManagement;
+
+/// <summary>
+/// Runtime scene loading tester - works in Play mode
+/// </summary>
+public class RuntimeSceneLoadTest : MonoBehaviour
+{
+    [Header("Runtime Scene Load Test")]
+    public string testSceneName = "TownSceen";
+
+    [ContextMenu("Test Scene Load")]
+    public void TestSceneLoad()
+    {
+        Debug.Log($"=== Testing Scene Load: {testSceneName} ===");
+
+        try
+        {
+            // Check if scene is in build settings by trying to get its build index
+            int buildIndex = SceneUtility.GetBuildIndexByScenePath($"Assets/Scenes/{testSceneName}.unity");
+
+            if (buildIndex >= 0)
+            {
+                Debug.Log($"✅ Scene found in Build Settings at index {buildIndex}");
+                Debug.Log($"Scene path: Assets/Scenes/{testSceneName}.unity");
+            }
+            else
+            {
+                Debug.LogError($"❌ Scene NOT found in Build Settings!");
+                Debug.LogError($"Add 'Assets/Scenes/{testSceneName}.unity' to Build Settings");
+                Debug.LogError("Go to: File > Build Settings > Add Open Scenes (or drag scene files)");
+                return;
+            }
+
+            // Actually try to load the scene (this will happen)
+            Debug.Log($"🚀 Loading scene: {testSceneName}");
+            SceneManager.LoadScene(testSceneName);
+
+        }
+        catch (System.Exception e)
+        {
+            Debug.LogError($"❌ Scene loading failed: {e.Message}");
+            Debug.LogError("Most likely cause: Scene not in Build Settings");
+        }
+    }
+
+    [ContextMenu("List All Scenes in Build")]
+    public void ListAllScenesInBuild()
+    {
+        Debug.Log("=== All Scenes in Build Settings ===");
+
+        int sceneCount = SceneManager.sceneCountInBuildSettings;
+        Debug.Log($"Total scenes in build: {sceneCount}");
+
+        for (int i = 0; i < sceneCount; i++)
+        {
+            string scenePath = SceneUtility.GetScenePathByBuildIndex(i);
+            string sceneName = System.IO.Path.GetFileNameWithoutExtension(scenePath);
+            Debug.Log($"  [{i}] {sceneName} ({scenePath})");
+        }
+
+        if (sceneCount == 0)
+        {
+            Debug.LogError("❌ NO SCENES in Build Settings!");
+            Debug.LogError("Go to File > Build Settings and add your scenes");
+        }
+    }
+
+    void Update()
+    {
+        // Quick test keys
+        if (Input.GetKeyDown(KeyCode.F12))
+        {
+            TestSceneLoad();
+        }
+
+        if (Input.GetKeyDown(KeyCode.F11))
+        {
+            ListAllScenesInBuild();
+        }
+    }
+
+    void OnGUI()
+    {
+        GUILayout.BeginArea(new Rect(Screen.width - 250, Screen.height - 150, 240, 130));
+        GUILayout.BeginVertical("box");
+
+        GUILayout.Label("Scene Load Tester", new GUIStyle(GUI.skin.label) { fontSize = 11, fontStyle = FontStyle.Bold });
+
+        if (GUILayout.Button($"Test Load {testSceneName} (F12)"))
+        {
+            TestSceneLoad();
+        }
+
+        if (GUILayout.Button("List Build Scenes (F11)"))
+        {
+            ListAllScenesInBuild();
+        }
+
+        GUILayout.Space(5);
+        GUILayout.Label("If test fails:", new GUIStyle(GUI.skin.label) { fontSize = 9, fontStyle = FontStyle.Bold });
+        GUILayout.Label("File > Build Settings", new GUIStyle(GUI.skin.label) { fontSize = 9 });
+        GUILayout.Label("Add scenes to list", new GUIStyle(GUI.skin.label) { fontSize = 9 });
+
+        GUILayout.EndVertical();
+        GUILayout.EndArea();
+    }
+}

+ 186 - 0
Assets/Scripts/Map/SceneBuildSettingsChecker.cs

@@ -0,0 +1,186 @@
+using UnityEngine;
+using UnityEditor;
+using System.Linq;
+
+/// <summary>
+/// Unity Editor script to check and fix Build Settings for scene loading
+/// </summary>
+public class SceneBuildSettingsChecker : MonoBehaviour
+{
+    [Header("Scene Build Settings Checker")]
+    [TextArea(3, 5)]
+    public string instructions = "This script checks if required scenes are in Build Settings.\nUse the buttons below to check and fix issues.";
+
+    [ContextMenu("Check Build Settings")]
+    public void CheckBuildSettings()
+    {
+        Debug.Log("=== Checking Build Settings ===");
+
+#if UNITY_EDITOR
+        // Get current build settings
+        var scenes = EditorBuildSettings.scenes;
+        
+        Debug.Log($"Current scenes in Build Settings: {scenes.Length}");
+        
+        foreach (var scene in scenes)
+        {
+            Debug.Log($"  - {scene.path} (enabled: {scene.enabled})");
+        }
+        
+        // Check specific scenes we need
+        string[] requiredScenes = { "TownSceen", "MapScene2" };
+        
+        foreach (string sceneName in requiredScenes)
+        {
+            bool found = scenes.Any(s => s.path.Contains(sceneName) && s.enabled);
+            
+            if (found)
+            {
+                Debug.Log($"✅ {sceneName} found in Build Settings");
+            }
+            else
+            {
+                Debug.LogError($"❌ {sceneName} NOT found in Build Settings!");
+                Debug.LogError($"   Add Assets/Scenes/{sceneName}.unity to Build Settings");
+            }
+        }
+        
+        Debug.Log("=== Build Settings Check Complete ===");
+        Debug.Log("To fix: Go to File > Build Settings and drag scene files into the list");
+#else
+        Debug.LogWarning("Build Settings can only be checked in Editor mode");
+#endif
+    }
+
+    [ContextMenu("Auto Fix Build Settings")]
+    public void AutoFixBuildSettings()
+    {
+#if UNITY_EDITOR
+        Debug.Log("=== Auto-fixing Build Settings ===");
+        
+        // Define scenes that should be in build settings
+        string[] sceneNames = { 
+            "TitleScreenScene", 
+            "MainTeamSelectScene", 
+            "MapScene2", 
+            "TownSceen", 
+            "BattleScene",
+            "BattleSetupMenu"
+        };
+        
+        var currentScenes = EditorBuildSettings.scenes.ToList();
+        bool addedAny = false;
+        
+        foreach (string sceneName in sceneNames)
+        {
+            string scenePath = $"Assets/Scenes/{sceneName}.unity";
+            
+            // Check if scene already exists in build settings
+            bool alreadyExists = currentScenes.Any(s => s.path == scenePath);
+            
+            if (!alreadyExists)
+            {
+                // Check if scene file exists
+                if (System.IO.File.Exists(scenePath))
+                {
+                    var newScene = new EditorBuildSettingsScene(scenePath, true);
+                    currentScenes.Add(newScene);
+                    addedAny = true;
+                    Debug.Log($"✅ Added {sceneName} to Build Settings");
+                }
+                else
+                {
+                    Debug.LogWarning($"⚠️ Scene file not found: {scenePath}");
+                }
+            }
+            else
+            {
+                Debug.Log($"✅ {sceneName} already in Build Settings");
+            }
+        }
+        
+        if (addedAny)
+        {
+            EditorBuildSettings.scenes = currentScenes.ToArray();
+            Debug.Log("🎯 Build Settings updated successfully!");
+            Debug.Log("Scenes are now ready for SceneManager.LoadScene()");
+        }
+        else
+        {
+            Debug.Log("ℹ️ No changes needed - all scenes already in Build Settings");
+        }
+        
+        // Re-check to confirm
+        CheckBuildSettings();
+#else
+        Debug.LogWarning("Build Settings can only be modified in Editor mode");
+#endif
+    }
+
+    [ContextMenu("Test Scene Loading")]
+    public void TestSceneLoading()
+    {
+        Debug.Log("=== Testing Scene Loading ===");
+
+        // Test if we can load TownSceen
+        string sceneName = "TownSceen";
+
+        try
+        {
+            // This would actually load the scene, so we'll just check if it would work
+            Debug.Log($"Attempting to load scene: {sceneName}");
+
+            // Check Application.CanStreamedLevelBeLoaded for older Unity versions
+            // or just try the load directly
+#if UNITY_EDITOR
+            var scenes = UnityEditor.EditorBuildSettings.scenes;
+            bool foundInBuild = scenes.Any(s => s.path.Contains(sceneName) && s.enabled);
+            
+            if (foundInBuild)
+            {
+                Debug.Log($"✅ Scene {sceneName} should load successfully");
+                Debug.Log("You can now test entering settlements!");
+            }
+            else
+            {
+                Debug.LogError($"❌ Scene {sceneName} not properly configured in Build Settings");
+            }
+#endif
+        }
+        catch (System.Exception e)
+        {
+            Debug.LogError($"❌ Scene loading test failed: {e.Message}");
+        }
+    }
+
+    void OnGUI()
+    {
+        GUILayout.BeginArea(new Rect(10, Screen.height - 200, 300, 180));
+        GUILayout.BeginVertical("box");
+
+        GUILayout.Label("Scene Build Settings Fixer", new GUIStyle(GUI.skin.label) { fontSize = 12, fontStyle = FontStyle.Bold });
+
+        if (GUILayout.Button("Check Build Settings"))
+        {
+            CheckBuildSettings();
+        }
+
+        if (GUILayout.Button("Auto Fix Build Settings"))
+        {
+            AutoFixBuildSettings();
+        }
+
+        if (GUILayout.Button("Test Scene Loading"))
+        {
+            TestSceneLoading();
+        }
+
+        GUILayout.Space(5);
+        GUILayout.Label("Manual Fix:", new GUIStyle(GUI.skin.label) { fontSize = 10, fontStyle = FontStyle.Bold });
+        GUILayout.Label("File > Build Settings", new GUIStyle(GUI.skin.label) { fontSize = 10 });
+        GUILayout.Label("Drag scenes into list", new GUIStyle(GUI.skin.label) { fontSize = 10 });
+
+        GUILayout.EndVertical();
+        GUILayout.EndArea();
+    }
+}

+ 148 - 0
Assets/Scripts/Map/SettlementDetectionHotfix.cs

@@ -0,0 +1,148 @@
+using UnityEngine;
+
+/// <summary>
+/// Temporary fix to force settlement detection to work
+/// This patches the coordinate conversion issue
+/// </summary>
+public class SettlementDetectionHotfix : MonoBehaviour
+{
+    [Header("Settlement Detection Hotfix")]
+    [Tooltip("Force settlement detection to work by improving coordinate conversion")]
+    public bool enableHotfix = true;
+
+    private SettlementInteractionManager settlementManager;
+
+    void Start()
+    {
+        settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
+        if (settlementManager != null && enableHotfix)
+        {
+            Debug.Log("[Hotfix] Settlement detection hotfix enabled");
+        }
+    }
+
+    void Update()
+    {
+        if (!enableHotfix || settlementManager == null) return;
+
+        // Check if we should manually trigger settlement detection
+        var teamMarker = GameObject.Find("TeamMarker");
+        if (teamMarker == null) return;
+
+        Vector3 teamPos = teamMarker.transform.position;
+        Vector2Int mapPos = new Vector2Int(
+            Mathf.RoundToInt(teamPos.x),
+            Mathf.RoundToInt(teamPos.z)
+        );
+
+        // Force check the exact coordinate and nearby coordinates
+        var mapMaker = FindFirstObjectByType<MapMaker2>();
+        if (mapMaker?.GetMapData() != null)
+        {
+            var mapData = mapMaker.GetMapData();
+
+            // Check current position and all adjacent positions
+            Settlement foundSettlement = null;
+
+            for (int dx = -1; dx <= 1; dx++)
+            {
+                for (int dy = -1; dy <= 1; dy++)
+                {
+                    Vector2Int checkPos = new Vector2Int(mapPos.x + dx, mapPos.y + dy);
+                    var settlement = mapData.GetSettlementAt(checkPos, 0.1f); // Very tight tolerance
+
+                    if (settlement != null)
+                    {
+                        foundSettlement = settlement;
+                        break;
+                    }
+                }
+                if (foundSettlement != null) break;
+            }
+
+            // If we found a settlement but the manager doesn't detect it, force the detection
+            var currentDetected = settlementManager.GetCurrentNearbySettlement();
+
+            if (foundSettlement != null && currentDetected == null)
+            {
+                Debug.Log($"[Hotfix] Forcing settlement detection: {foundSettlement.name} at {foundSettlement.position}");
+
+                // Force manual entry when E is pressed
+                if (Input.GetKeyDown(KeyCode.E))
+                {
+                    Debug.Log($"[Hotfix] Manually entering settlement: {foundSettlement.name}");
+                    settlementManager.EnterSettlement(foundSettlement);
+                }
+            }
+        }
+    }
+
+    [ContextMenu("Force Settlement Detection Now")]
+    public void ForceDetectionNow()
+    {
+        var teamMarker = GameObject.Find("TeamMarker");
+        var mapMaker = FindFirstObjectByType<MapMaker2>();
+
+        if (teamMarker == null || mapMaker?.GetMapData() == null)
+        {
+            Debug.LogError("[Hotfix] Missing components for detection");
+            return;
+        }
+
+        Vector3 teamPos = teamMarker.transform.position;
+        Vector2Int mapPos = new Vector2Int(
+            Mathf.RoundToInt(teamPos.x),
+            Mathf.RoundToInt(teamPos.z)
+        );
+
+        Debug.Log($"[Hotfix] Checking position {mapPos} (world {teamPos})");
+
+        var mapData = mapMaker.GetMapData();
+        var allSettlements = mapData.GetAllSettlements();
+
+        foreach (var settlement in allSettlements)
+        {
+            float distance = Vector2Int.Distance(mapPos, settlement.position);
+            Debug.Log($"[Hotfix] Settlement '{settlement.name}' at {settlement.position} - Distance: {distance:F2}");
+
+            if (distance <= 1.5f)
+            {
+                Debug.Log($"[Hotfix] 🎯 FOUND NEARBY: {settlement.name}");
+
+                if (settlementManager != null)
+                {
+                    Debug.Log($"[Hotfix] Manually entering settlement: {settlement.name}");
+                    settlementManager.EnterSettlement(settlement);
+                    return;
+                }
+            }
+        }
+
+        Debug.Log("[Hotfix] No settlement found within range");
+    }
+
+    void OnGUI()
+    {
+        if (!enableHotfix) return;
+
+        GUILayout.BeginArea(new Rect(Screen.width - 300, 10, 280, 100));
+        GUILayout.BeginVertical("box");
+
+        GUILayout.Label("Settlement Detection Hotfix", new GUIStyle(GUI.skin.label) { fontSize = 12, fontStyle = FontStyle.Bold });
+
+        if (GUILayout.Button("Force Enter Settlement"))
+        {
+            ForceDetectionNow();
+        }
+
+        var teamMarker = GameObject.Find("TeamMarker");
+        if (teamMarker != null)
+        {
+            Vector3 pos = teamMarker.transform.position;
+            GUILayout.Label($"Position: ({pos.x:F0}, {pos.z:F0})", new GUIStyle(GUI.skin.label) { fontSize = 10 });
+        }
+
+        GUILayout.EndVertical();
+        GUILayout.EndArea();
+    }
+}

+ 250 - 0
Assets/Scripts/Map/SettlementInteractionCompleteFix.cs

@@ -0,0 +1,250 @@
+using UnityEngine;
+using UnityEngine.UIElements;
+
+/// <summary>
+/// Comprehensive fix for settlement interaction detection and UI updates
+/// This component forces the settlement detection system to work properly
+/// </summary>
+public class SettlementInteractionCompleteFix : MonoBehaviour
+{
+    [Header("Complete Settlement Interaction Fix")]
+    [Tooltip("Enable comprehensive settlement detection fix")]
+    public bool enableFix = true;
+
+    [Tooltip("Force UI updates even when manager doesn't detect settlements")]
+    public bool forceUIUpdates = true;
+
+    [Tooltip("Debug output level")]
+    public bool verboseDebug = true;
+
+    private SettlementInteractionManager manager;
+    private SettlementInteractionUI settlementUI;
+    private Transform teamMarker;
+    private MapMaker2 mapMaker;
+    private Settlement lastDetectedSettlement;
+
+    void Start()
+    {
+        if (!enableFix) return;
+
+        // Find all components
+        manager = FindFirstObjectByType<SettlementInteractionManager>();
+        settlementUI = FindFirstObjectByType<SettlementInteractionUI>();
+        teamMarker = GameObject.Find("TeamMarker")?.transform;
+        mapMaker = FindFirstObjectByType<MapMaker2>();
+
+        LogDebug("=== Settlement Interaction Complete Fix Started ===");
+        LogDebug($"Manager found: {manager != null}");
+        LogDebug($"UI found: {settlementUI != null}");
+        LogDebug($"TeamMarker found: {teamMarker != null}");
+        LogDebug($"MapMaker found: {mapMaker != null}");
+
+        if (manager != null)
+        {
+            // Ensure debug logging is enabled
+            manager.enableDebugLogs = true;
+            LogDebug("Enabled debug logging on SettlementInteractionManager");
+        }
+    }
+
+    void Update()
+    {
+        if (!enableFix || manager == null || teamMarker == null || mapMaker?.GetMapData() == null)
+            return;
+
+        // Manual settlement detection that actually works
+        Settlement currentSettlement = DetectNearbySettlement();
+
+        // Check if settlement detection changed
+        if (currentSettlement != lastDetectedSettlement)
+        {
+            if (lastDetectedSettlement != null)
+            {
+                LogDebug($"Left settlement: {lastDetectedSettlement.name}");
+
+                // Force trigger OnSettlementLeft event
+                if (forceUIUpdates && settlementUI != null)
+                {
+                    settlementUI.ForceHideUI();
+                }
+
+                // Try to trigger manager's event
+                try
+                {
+                    manager.OnSettlementLeft?.Invoke();
+                }
+                catch (System.Exception e)
+                {
+                    LogDebug($"Error invoking OnSettlementLeft: {e.Message}");
+                }
+            }
+
+            lastDetectedSettlement = currentSettlement;
+
+            if (currentSettlement != null)
+            {
+                LogDebug($"Detected settlement: {currentSettlement.name} ({currentSettlement.Type})");
+
+                // Force trigger OnSettlementDetected event
+                if (forceUIUpdates && settlementUI != null)
+                {
+                    // Update UI manually
+                    UpdateSettlementUI(currentSettlement);
+                }
+
+                // Try to trigger manager's event
+                try
+                {
+                    manager.OnSettlementDetected?.Invoke(currentSettlement);
+                }
+                catch (System.Exception e)
+                {
+                    LogDebug($"Error invoking OnSettlementDetected: {e.Message}");
+                }
+            }
+        }
+
+        // Handle input manually if manager doesn't
+        if (currentSettlement != null && Input.GetKeyDown(KeyCode.E))
+        {
+            LogDebug($"Manual E key detection - entering {currentSettlement.name}");
+            manager.EnterSettlement(currentSettlement);
+        }
+    }
+
+    private Settlement DetectNearbySettlement()
+    {
+        Vector3 teamPos = teamMarker.position;
+        Vector2Int mapPos = new Vector2Int(
+            Mathf.RoundToInt(teamPos.x),
+            Mathf.RoundToInt(teamPos.z)
+        );
+
+        var mapData = mapMaker.GetMapData();
+        if (mapData == null) return null;
+
+        // Check current position and surrounding area
+        for (int dx = -2; dx <= 2; dx++)
+        {
+            for (int dy = -2; dy <= 2; dy++)
+            {
+                Vector2Int checkPos = new Vector2Int(mapPos.x + dx, mapPos.y + dy);
+                var settlement = mapData.GetSettlementAt(checkPos, 0.5f);
+
+                if (settlement != null)
+                {
+                    float distance = Vector2Int.Distance(mapPos, settlement.position);
+                    if (distance <= 2f) // Within interaction range
+                    {
+                        return settlement;
+                    }
+                }
+            }
+        }
+
+        return null;
+    }
+
+    private void UpdateSettlementUI(Settlement settlement)
+    {
+        if (settlementUI == null) return;
+
+        // Force show UI
+        settlementUI.ForceShowUI();
+
+        // Try to update UI elements directly
+        try
+        {
+            var uiDoc = settlementUI.GetComponent<UIDocument>();
+            if (uiDoc != null)
+            {
+                var root = uiDoc.rootVisualElement;
+
+                var nameLabel = root.Q<UnityEngine.UIElements.Label>("SettlementName");
+                if (nameLabel != null)
+                {
+                    nameLabel.text = settlement.name;
+                    LogDebug($"Updated settlement name to: {settlement.name}");
+                }
+
+                var instructionLabel = root.Q<UnityEngine.UIElements.Label>("InteractionInstruction");
+                if (instructionLabel != null)
+                {
+                    string settlementType = settlement.Type == SettlementType.Town ? "Town" : "Village";
+                    instructionLabel.text = $"Press E to enter {settlementType}";
+                    LogDebug($"Updated instruction text");
+                }
+
+                var container = root.Q<UnityEngine.UIElements.VisualElement>("SettlementPrompt");
+                if (container != null)
+                {
+                    container.style.display = UnityEngine.UIElements.DisplayStyle.Flex;
+                }
+            }
+        }
+        catch (System.Exception e)
+        {
+            LogDebug($"Error updating UI: {e.Message}");
+        }
+    }
+
+    private void LogDebug(string message)
+    {
+        if (verboseDebug)
+        {
+            Debug.Log($"[SettlementFix] {message}");
+        }
+    }
+
+    [ContextMenu("Force Detect Settlement Now")]
+    public void ForceDetectNow()
+    {
+        var settlement = DetectNearbySettlement();
+        if (settlement != null)
+        {
+            LogDebug($"Force detected: {settlement.name}");
+            UpdateSettlementUI(settlement);
+        }
+        else
+        {
+            LogDebug("No settlement detected at current position");
+            if (settlementUI != null)
+            {
+                settlementUI.ForceHideUI();
+            }
+        }
+    }
+
+    void OnGUI()
+    {
+        if (!enableFix) return;
+
+        GUILayout.BeginArea(new Rect(10, 300, 350, 120));
+        GUILayout.BeginVertical("box");
+
+        GUILayout.Label("Settlement Complete Fix", new GUIStyle(GUI.skin.label) { fontSize = 12, fontStyle = FontStyle.Bold });
+
+        if (GUILayout.Button("Force Detect Settlement"))
+        {
+            ForceDetectNow();
+        }
+
+        if (lastDetectedSettlement != null)
+        {
+            GUILayout.Label($"Current: {lastDetectedSettlement.name}", new GUIStyle(GUI.skin.label) { fontSize = 10 });
+        }
+        else
+        {
+            GUILayout.Label("No settlement detected", new GUIStyle(GUI.skin.label) { fontSize = 10 });
+        }
+
+        if (teamMarker != null)
+        {
+            Vector3 pos = teamMarker.position;
+            GUILayout.Label($"Position: ({pos.x:F0}, {pos.z:F0})", new GUIStyle(GUI.skin.label) { fontSize = 10 });
+        }
+
+        GUILayout.EndVertical();
+        GUILayout.EndArea();
+    }
+}

+ 254 - 0
Assets/Scripts/Map/SettlementInteractionDebugger.cs

@@ -0,0 +1,254 @@
+using UnityEngine;
+
+/// <summary>
+/// Debug script to diagnose settlement interaction issues
+/// Add this to a GameObject in MapScene2 to test the settlement interaction system
+/// </summary>
+public class SettlementInteractionDebugger : MonoBehaviour
+{
+    [Header("Debug Settings")]
+    public bool enableDebugOverlay = true;
+    public bool logEveryFrame = false;
+
+    private SettlementInteractionManager interactionManager;
+    private SettlementInteractionUI interactionUI;
+    private Transform teamMarker;
+
+    void Start()
+    {
+        Debug.Log("=== Settlement Interaction Debugger Started ===");
+
+        // Find components
+        interactionManager = FindFirstObjectByType<SettlementInteractionManager>();
+        interactionUI = FindFirstObjectByType<SettlementInteractionUI>();
+        teamMarker = GameObject.Find("TeamMarker")?.transform;
+
+        // Initial diagnostics
+        DiagnoseComponents();
+    }
+
+    void Update()
+    {
+        if (logEveryFrame)
+        {
+            LogCurrentState();
+        }
+
+        // Test manual input
+        if (Input.GetKeyDown(KeyCode.F1))
+        {
+            TestSettlementDetection();
+        }
+
+        if (Input.GetKeyDown(KeyCode.F2))
+        {
+            TestManualEntry();
+        }
+    }
+
+    private void DiagnoseComponents()
+    {
+        Debug.Log("=== Component Diagnosis ===");
+
+        // Check SettlementInteractionManager
+        if (interactionManager != null)
+        {
+            Debug.Log("✅ SettlementInteractionManager found");
+            Debug.Log($"   - GameObject: {interactionManager.gameObject.name}");
+            Debug.Log($"   - Enabled: {interactionManager.enabled}");
+            Debug.Log($"   - Active: {interactionManager.gameObject.activeSelf}");
+            Debug.Log($"   - TeamMarker assigned: {interactionManager.teamMarker != null}");
+            Debug.Log($"   - Interaction Distance: {interactionManager.interactionDistance}");
+            Debug.Log($"   - Enter Key: {interactionManager.enterSettlementKey}");
+            Debug.Log($"   - Debug Logs Enabled: {interactionManager.enableDebugLogs}");
+
+            // Check if MapData is accessible
+            var mapMaker = FindFirstObjectByType<MapMaker2>();
+            if (mapMaker != null)
+            {
+                var mapData = mapMaker.GetMapData();
+                Debug.Log($"   - MapData available: {mapData != null}");
+                if (mapData != null)
+                {
+                    var settlements = mapData.GetAllSettlements();
+                    Debug.Log($"   - Settlements count: {settlements?.Count ?? 0}");
+                }
+            }
+            else
+            {
+                Debug.LogWarning("   - MapMaker2 not found!");
+            }
+        }
+        else
+        {
+            Debug.LogError("❌ SettlementInteractionManager NOT FOUND!");
+            Debug.LogError("   Make sure to add SettlementInteractionManager component to a GameObject in MapScene2");
+        }
+
+        // Check SettlementInteractionUI
+        if (interactionUI != null)
+        {
+            Debug.Log("✅ SettlementInteractionUI found");
+            Debug.Log($"   - GameObject: {interactionUI.gameObject.name}");
+        }
+        else
+        {
+            Debug.LogWarning("⚠️ SettlementInteractionUI not found");
+        }
+
+        // Check TeamMarker
+        if (teamMarker != null)
+        {
+            Debug.Log("✅ TeamMarker found");
+            Debug.Log($"   - Position: {teamMarker.position}");
+        }
+        else
+        {
+            Debug.LogError("❌ TeamMarker GameObject not found!");
+        }
+
+        Debug.Log("=== End Diagnosis ===");
+        Debug.Log("Press F1 to test settlement detection");
+        Debug.Log("Press F2 to test manual settlement entry");
+    }
+
+    private void LogCurrentState()
+    {
+        if (interactionManager == null || teamMarker == null) return;
+
+        var currentSettlement = interactionManager.GetCurrentNearbySettlement();
+        Debug.Log($"[Frame] TeamMarker: {teamMarker.position}, Current Settlement: {(currentSettlement?.name ?? "None")}");
+    }
+
+    [ContextMenu("Test Settlement Detection")]
+    public void TestSettlementDetection()
+    {
+        Debug.Log("=== Testing Settlement Detection ===");
+
+        if (interactionManager == null)
+        {
+            Debug.LogError("No SettlementInteractionManager found!");
+            return;
+        }
+
+        if (teamMarker == null)
+        {
+            Debug.LogError("No TeamMarker found!");
+            return;
+        }
+
+        var currentSettlement = interactionManager.GetCurrentNearbySettlement();
+        Debug.Log($"Current nearby settlement: {(currentSettlement?.name ?? "None")}");
+
+        // Check if UI is showing
+        if (interactionUI != null)
+        {
+            Debug.Log("SettlementInteractionUI is present and should be handling events");
+        }
+
+        // Manual coordinate check
+        Vector2 teamWorldPos = new Vector2(teamMarker.position.x, teamMarker.position.z);
+        Debug.Log($"TeamMarker world position: {teamWorldPos}");
+
+        // Try to find MapData and check settlements manually
+        var mapMaker = FindFirstObjectByType<MapMaker2>();
+        if (mapMaker != null)
+        {
+            var mapData = mapMaker.GetMapData();
+            if (mapData != null)
+            {
+                var settlements = mapData.GetAllSettlements();
+                Debug.Log($"Total settlements in map: {settlements?.Count ?? 0}");
+
+                if (settlements != null && settlements.Count > 0)
+                {
+                    foreach (var settlement in settlements)
+                    {
+                        float distance = Vector2.Distance(teamWorldPos, new Vector2(settlement.position.x, settlement.position.y));
+                        Debug.Log($"Settlement '{settlement.name}' at {settlement.position} - Distance: {distance:F2}");
+                    }
+                }
+            }
+        }
+    }
+
+    [ContextMenu("Test Manual Entry")]
+    public void TestManualEntry()
+    {
+        Debug.Log("=== Testing Manual Settlement Entry ===");
+
+        if (interactionManager != null)
+        {
+            interactionManager.TestEnterCurrentSettlement();
+        }
+        else
+        {
+            Debug.LogError("No SettlementInteractionManager found!");
+        }
+    }
+
+    [ContextMenu("Force Enable Debug Logging")]
+    public void ForceEnableDebugLogging()
+    {
+        if (interactionManager != null)
+        {
+            interactionManager.enableDebugLogs = true;
+            Debug.Log("Debug logging enabled on SettlementInteractionManager");
+        }
+    }
+
+    [ContextMenu("Test Input Detection")]
+    public void TestInputDetection()
+    {
+        Debug.Log("=== Testing Input Detection ===");
+        Debug.Log($"Input.GetKeyDown(KeyCode.E): {Input.GetKeyDown(KeyCode.E)}");
+        Debug.Log($"Input.GetKey(KeyCode.E): {Input.GetKey(KeyCode.E)}");
+        Debug.Log($"Input.inputString: '{Input.inputString}'");
+    }
+
+    void OnGUI()
+    {
+        if (!enableDebugOverlay) return;
+
+        GUILayout.BeginArea(new Rect(10, 10, 400, 300));
+        GUILayout.BeginVertical("box");
+
+        GUILayout.Label("Settlement Interaction Debug", new GUIStyle(GUI.skin.label) { fontSize = 16, fontStyle = FontStyle.Bold });
+
+        if (interactionManager != null)
+        {
+            var currentSettlement = interactionManager.GetCurrentNearbySettlement();
+            GUILayout.Label($"Current Settlement: {(currentSettlement?.name ?? "None")}");
+
+            if (teamMarker != null)
+            {
+                GUILayout.Label($"TeamMarker Position: {teamMarker.position}");
+            }
+
+            GUILayout.Space(10);
+
+            if (GUILayout.Button("Test Settlement Detection (F1)"))
+            {
+                TestSettlementDetection();
+            }
+
+            if (GUILayout.Button("Test Manual Entry (F2)"))
+            {
+                TestManualEntry();
+            }
+
+            if (GUILayout.Button("Force Debug Logging"))
+            {
+                ForceEnableDebugLogging();
+            }
+        }
+        else
+        {
+            GUILayout.Label("❌ SettlementInteractionManager NOT FOUND!", new GUIStyle(GUI.skin.label) { normal = { textColor = Color.red } });
+            GUILayout.Label("Add SettlementInteractionManager component to a GameObject in this scene");
+        }
+
+        GUILayout.EndVertical();
+        GUILayout.EndArea();
+    }
+}

+ 222 - 0
Assets/Scripts/Map/SettlementInteractionFixer.cs

@@ -0,0 +1,222 @@
+using UnityEngine;
+
+/// <summary>
+/// Quick fix to properly setup SettlementInteractionManager references
+/// Run this in play mode to fix the settlement interaction system
+/// </summary>
+public class SettlementInteractionFixer : MonoBehaviour
+{
+    [Header("Fix Settlement Interaction")]
+    [Space]
+    [TextArea(3, 5)]
+    public string instructions = "1. Run this in Play Mode\n2. Click 'Fix Settlement Interaction' button\n3. Move TeamMarker near settlements\n4. Press E to enter";
+
+    [ContextMenu("Fix Settlement Interaction")]
+    public void FixSettlementInteraction()
+    {
+        Debug.Log("=== Fixing Settlement Interaction ===");
+
+        // Find components
+        var settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
+        var teamMarker = GameObject.Find("TeamMarker");
+        var mapMaker = FindFirstObjectByType<MapMaker2>();
+
+        if (settlementManager == null)
+        {
+            Debug.LogError("❌ SettlementInteractionManager not found! Create it first.");
+            return;
+        }
+
+        // Fix TeamMarker reference
+        if (teamMarker != null)
+        {
+            settlementManager.SetTeamMarker(teamMarker.transform);
+            Debug.Log("✅ TeamMarker reference set");
+        }
+        else
+        {
+            Debug.LogError("❌ TeamMarker GameObject not found!");
+        }
+
+        // Check MapMaker2 and MapData
+        if (mapMaker != null)
+        {
+            var mapData = mapMaker.GetMapData();
+            if (mapData != null)
+            {
+                var settlements = mapData.GetAllSettlements();
+                Debug.Log($"✅ MapData found with {settlements?.Count ?? 0} settlements");
+            }
+            else
+            {
+                Debug.LogError("❌ MapData is null!");
+            }
+        }
+        else
+        {
+            Debug.LogError("❌ MapMaker2 not found!");
+        }
+
+        // Force enable debug logging
+        settlementManager.enableDebugLogs = true;
+        Debug.Log("✅ Debug logging enabled");
+
+        // Test current position
+        if (teamMarker != null)
+        {
+            Vector3 teamPos = teamMarker.transform.position;
+            Debug.Log($"📍 TeamMarker position: {teamPos}");
+
+            // Force check for nearby settlements
+            var currentSettlement = settlementManager.GetCurrentNearbySettlement();
+            Debug.Log($"🏠 Current nearby settlement: {(currentSettlement?.name ?? "None")}");
+        }
+
+        Debug.Log("=== Fix Complete ===");
+        Debug.Log("Now move TeamMarker near a settlement and press E");
+    }
+
+    [ContextMenu("Test Settlement Detection")]
+    public void TestSettlementDetection()
+    {
+        var settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
+        var teamMarker = GameObject.Find("TeamMarker");
+        var mapMaker = FindFirstObjectByType<MapMaker2>();
+
+        if (settlementManager == null || teamMarker == null || mapMaker == null)
+        {
+            Debug.LogError("Missing components for testing!");
+            return;
+        }
+
+        Vector2 teamWorldPos = new Vector2(teamMarker.transform.position.x, teamMarker.transform.position.z);
+        Debug.Log($"🎯 TeamMarker world position: {teamWorldPos}");
+
+        // Convert to map coordinates manually to check conversion
+        float tileSize = 1f;
+        var mapVisualizer = FindFirstObjectByType<MapVisualizer>();
+        if (mapVisualizer != null && mapVisualizer.tileSize > 0)
+        {
+            tileSize = mapVisualizer.tileSize;
+            Debug.Log($"📏 MapVisualizer tile size: {tileSize}");
+        }
+        else
+        {
+            Debug.LogWarning("⚠️ MapVisualizer not found, using default tile size 1.0");
+        }
+
+        Vector2Int mapPos = new Vector2Int(
+            Mathf.RoundToInt(teamWorldPos.x / tileSize),
+            Mathf.RoundToInt(teamWorldPos.y / tileSize)
+        );
+        Debug.Log($"🗺️ Converted map position: {mapPos}");
+
+        // Test different coordinate interpretations
+        Vector2Int mapPosFloor = new Vector2Int(
+            Mathf.FloorToInt(teamWorldPos.x / tileSize),
+            Mathf.FloorToInt(teamWorldPos.y / tileSize)
+        );
+        Vector2Int mapPosCeil = new Vector2Int(
+            Mathf.CeilToInt(teamWorldPos.x / tileSize),
+            Mathf.CeilToInt(teamWorldPos.y / tileSize)
+        );
+        Debug.Log($"🔍 Alternative positions - Floor: {mapPosFloor}, Ceil: {mapPosCeil}");
+
+        // Check settlements manually
+        var mapData = mapMaker.GetMapData();
+        if (mapData != null)
+        {
+            var settlements = mapData.GetAllSettlements();
+            Debug.Log($"📊 Total settlements: {settlements?.Count ?? 0}");
+
+            if (settlements != null)
+            {
+                Debug.Log("🏘️ Checking all settlements:");
+                foreach (var settlement in settlements)
+                {
+                    float distanceRound = Vector2Int.Distance(mapPos, settlement.position);
+                    float distanceFloor = Vector2Int.Distance(mapPosFloor, settlement.position);
+                    float distanceCeil = Vector2Int.Distance(mapPosCeil, settlement.position);
+
+                    Debug.Log($"   '{settlement.name}' at {settlement.position}");
+                    Debug.Log($"     Round distance: {distanceRound:F2}");
+                    Debug.Log($"     Floor distance: {distanceFloor:F2}");
+                    Debug.Log($"     Ceil distance: {distanceCeil:F2}");
+
+                    if (distanceRound <= 2f || distanceFloor <= 2f || distanceCeil <= 2f)
+                    {
+                        Debug.Log($"🎯 WITHIN RANGE: {settlement.name}");
+
+                        // Test the exact method SettlementInteractionManager uses
+                        var foundSettlement = mapData.GetSettlementAt(mapPos, 2f);
+                        Debug.Log($"🔍 GetSettlementAt result: {foundSettlement?.name ?? "null"}");
+                    }
+                }
+
+                // Try to find settlements around the exact position (122, 71)
+                Debug.Log($"🔍 Checking exact position (122, 71):");
+                var exactSettlement = mapData.GetSettlementAt(new Vector2Int(122, 71), 2f);
+                Debug.Log($"   Settlement at (122, 71): {exactSettlement?.name ?? "None"}");
+            }
+        }
+    }
+
+    [ContextMenu("Force Manual Entry")]
+    public void ForceManualEntry()
+    {
+        var settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
+        if (settlementManager != null)
+        {
+            settlementManager.TestEnterCurrentSettlement();
+        }
+        else
+        {
+            Debug.LogError("SettlementInteractionManager not found!");
+        }
+    }
+
+    void Update()
+    {
+        // Show debug info on screen
+        if (Input.GetKeyDown(KeyCode.F9))
+        {
+            FixSettlementInteraction();
+        }
+
+        if (Input.GetKeyDown(KeyCode.F10))
+        {
+            TestSettlementDetection();
+        }
+
+        if (Input.GetKeyDown(KeyCode.F11))
+        {
+            ForceManualEntry();
+        }
+    }
+
+    void OnGUI()
+    {
+        GUILayout.BeginArea(new Rect(10, Screen.height - 150, 400, 140));
+        GUILayout.BeginVertical("box");
+
+        GUILayout.Label("Settlement Interaction Quick Fix", new GUIStyle(GUI.skin.label) { fontSize = 14, fontStyle = FontStyle.Bold });
+
+        if (GUILayout.Button("Fix Settlement Interaction (F9)"))
+        {
+            FixSettlementInteraction();
+        }
+
+        if (GUILayout.Button("Test Settlement Detection (F10)"))
+        {
+            TestSettlementDetection();
+        }
+
+        if (GUILayout.Button("Force Manual Entry (F11)"))
+        {
+            ForceManualEntry();
+        }
+
+        GUILayout.EndVertical();
+        GUILayout.EndArea();
+    }
+}

+ 409 - 0
Assets/Scripts/Map/SettlementInteractionManager.cs

@@ -0,0 +1,409 @@
+using UnityEngine;
+using UnityEngine.SceneManagement;
+using System.Collections.Generic;
+using System.Linq;
+
+/// <summary>
+/// Manages settlement interaction on the map - detects when TeamMarker is over a settlement
+/// and allows entering the town scene with proper context setup
+/// </summary>
+public class SettlementInteractionManager : MonoBehaviour
+{
+    [Header("Settlement Detection")]
+    [Tooltip("The TeamMarker GameObject to track")]
+    public Transform teamMarker;
+
+    [Tooltip("How close the team marker needs to be to settlement center to interact")]
+    public float interactionDistance = 2f;
+
+    [Tooltip("Key to press to enter settlement")]
+    public KeyCode enterSettlementKey = KeyCode.E;
+
+    [Tooltip("Automatically enter settlement when TeamMarker stops moving")]
+    public bool autoEnterOnStop = false;
+
+    [Tooltip("Time to wait before auto-entering (if enabled)")]
+    public float autoEnterDelay = 1f;
+
+    [Header("UI")]
+    [Tooltip("UI element to show when near settlement (optional)")]
+    public GameObject interactionPrompt;
+
+    [Header("Scene Loading")]
+    [Tooltip("Name of the town scene to load")]
+    public string townSceneName = "TownSceen";
+
+    [Header("Debug")]
+    public bool enableDebugLogs = true;
+
+    [Header("Exit Protection")]
+    [Tooltip("Cooldown period after exiting a settlement before allowing re-entry")]
+    public float exitCooldown = 3f;
+
+    // Private fields
+    private MapMaker2 mapMaker;
+    private MapData mapData;
+    private Settlement currentNearbySettlement;
+    private Vector3 lastTeamMarkerPosition;
+    private float timeStationary = 0f;
+    private float lastExitTime = -999f; // Time when last exited a settlement
+    private string lastExitedSettlement = ""; // Name of last exited settlement
+
+    // Events
+    public System.Action<Settlement> OnSettlementDetected;
+    public System.Action OnSettlementLeft;
+    public System.Action<Settlement> OnSettlementEntered;
+
+    void Awake()
+    {
+        // Check if we're returning from a town scene
+        var settlementContext = FindFirstObjectByType<SettlementContext>();
+        if (settlementContext != null && !string.IsNullOrEmpty(settlementContext.settlementName))
+        {
+            // We just returned from a settlement - set cooldown
+            lastExitTime = Time.time;
+            lastExitedSettlement = settlementContext.settlementName;
+            LogDebug($"COOLDOWN: Detected return from settlement: {settlementContext.settlementName} - applying {exitCooldown}s cooldown");
+        }
+        else
+        {
+            LogDebug("COOLDOWN: No settlement context found - normal startup");
+        }
+    }
+
+    void Start()
+    {
+        InitializeComponents();
+    }
+
+    void Update()
+    {
+        // Retry MapData connection if it failed initially
+        if (mapData == null && mapMaker != null)
+        {
+            mapData = mapMaker.GetMapData();
+            if (mapData != null)
+            {
+                LogDebug($"MapData connection retry successful - Map size: {mapData.Width}x{mapData.Height}");
+            }
+        }
+
+        if (teamMarker == null || mapData == null) return;
+
+        CheckForSettlementInteraction();
+        HandleInput();
+        // Remove auto-enter functionality - only manual E-key entry
+        // HandleAutoEnter();
+    }
+
+    /// <summary>
+    /// Initialize required components and references
+    /// </summary>
+    private void InitializeComponents()
+    {
+        // Find TeamMarker if not assigned
+        if (teamMarker == null)
+        {
+            GameObject teamMarkerObj = GameObject.Find("TeamMarker");
+            if (teamMarkerObj != null)
+            {
+                teamMarker = teamMarkerObj.transform;
+                LogDebug("Found TeamMarker automatically");
+            }
+            else
+            {
+                LogDebug("TeamMarker not found - assign manually or create GameObject named 'TeamMarker'");
+                // Don't return - continue to find MapMaker2 so we can retry later
+            }
+        }
+
+        // Find MapMaker2
+        mapMaker = FindFirstObjectByType<MapMaker2>();
+        if (mapMaker != null)
+        {
+            mapData = mapMaker.GetMapData();
+            LogDebug($"Connected to MapMaker2 - Map size: {mapData?.Width}x{mapData?.Height}");
+        }
+        else
+        {
+            LogDebug("MapMaker2 not found - settlement detection will not work");
+        }
+
+        // Initialize UI
+        if (interactionPrompt != null)
+        {
+            interactionPrompt.SetActive(false);
+        }
+
+        lastTeamMarkerPosition = teamMarker.position;
+    }
+
+    /// <summary>
+    /// Check if TeamMarker is near any settlement
+    /// </summary>
+    private void CheckForSettlementInteraction()
+    {
+        Vector2 teamWorldPos = new Vector2(teamMarker.position.x, teamMarker.position.z);
+
+        // Convert world position to map coordinates
+        Vector2Int mapPos = WorldToMapCoordinates(teamWorldPos);
+
+        // Find nearby settlement
+        Settlement nearbySettlement = FindNearestSettlement(mapPos);
+
+        // Handle settlement detection changes
+        if (nearbySettlement != currentNearbySettlement)
+        {
+            if (currentNearbySettlement != null)
+            {
+                OnSettlementLeft?.Invoke();
+                LogDebug($"Left settlement: {currentNearbySettlement.name}");
+            }
+
+            currentNearbySettlement = nearbySettlement;
+
+            if (currentNearbySettlement != null)
+            {
+                OnSettlementDetected?.Invoke(currentNearbySettlement);
+                LogDebug($"Near settlement: {currentNearbySettlement.name} ({currentNearbySettlement.Type})");
+            }
+
+            UpdateUI();
+        }
+    }
+
+    /// <summary>
+    /// Convert world coordinates to map tile coordinates
+    /// </summary>
+    private Vector2Int WorldToMapCoordinates(Vector2 worldPos)
+    {
+        // Get tile size from MapVisualizer if available
+        float tileSize = 1f;
+        var mapVisualizer = FindFirstObjectByType<MapVisualizer>();
+        if (mapVisualizer != null && mapVisualizer.tileSize > 0)
+        {
+            tileSize = mapVisualizer.tileSize;
+        }
+
+        return new Vector2Int(
+            Mathf.RoundToInt(worldPos.x / tileSize),
+            Mathf.RoundToInt(worldPos.y / tileSize)
+        );
+    }
+
+    /// <summary>
+    /// Find the nearest settlement to the given map position
+    /// </summary>
+    private Settlement FindNearestSettlement(Vector2Int mapPos)
+    {
+        if (mapData == null) return null;
+
+        // Only detect settlements when directly on the settlement tile (exact match)
+        Settlement exactMatch = mapData.GetSettlementAt(mapPos);
+        if (exactMatch != null)
+        {
+            // Check exit cooldown
+            if (exactMatch.name == lastExitedSettlement && Time.time - lastExitTime < exitCooldown)
+            {
+                float remainingCooldown = exitCooldown - (Time.time - lastExitTime);
+                LogDebug($"Settlement {exactMatch.name} on cooldown for {remainingCooldown:F1}s more");
+                return null;
+            }
+
+            LogDebug($"Direct settlement match: {exactMatch.name} at {mapPos}");
+            return exactMatch;
+        }
+
+        // No nearby search - only exact tile matches
+        return null;
+    }
+
+    /// <summary>
+    /// Handle input for settlement interaction
+    /// </summary>
+    private void HandleInput()
+    {
+        if (currentNearbySettlement != null && Input.GetKeyDown(enterSettlementKey))
+        {
+            EnterSettlement(currentNearbySettlement);
+        }
+    }
+
+    /// <summary>
+    /// Handle automatic settlement entry when stationary
+    /// </summary>
+    private void HandleAutoEnter()
+    {
+        if (!autoEnterOnStop || currentNearbySettlement == null) return;
+
+        // Check if team marker has moved
+        Vector3 currentPosition = teamMarker.position;
+        float movementDistance = Vector3.Distance(currentPosition, lastTeamMarkerPosition);
+
+        if (movementDistance < 0.1f) // Very small threshold for "stationary"
+        {
+            timeStationary += Time.deltaTime;
+
+            if (timeStationary >= autoEnterDelay)
+            {
+                EnterSettlement(currentNearbySettlement);
+                timeStationary = 0f; // Reset to prevent multiple entries
+            }
+        }
+        else
+        {
+            timeStationary = 0f; // Reset timer if moving
+        }
+
+        lastTeamMarkerPosition = currentPosition;
+    }
+
+    /// <summary>
+    /// Enter the specified settlement - setup context and load town scene
+    /// </summary>
+    public void EnterSettlement(Settlement settlement)
+    {
+        if (settlement == null) return;
+
+        LogDebug($"Entering settlement: {settlement.name} ({settlement.Type})");
+
+        // Determine if settlement has harbor (check if near water)
+        bool hasHarbor = DetermineHarborPresence(settlement);
+
+        // Set up SettlementContext
+        SetupSettlementContext(settlement, hasHarbor);
+
+        // Trigger event
+        OnSettlementEntered?.Invoke(settlement);
+
+        // Load town scene
+        LoadTownScene();
+    }
+
+    /// <summary>
+    /// Determine if settlement should have a harbor based on nearby terrain
+    /// </summary>
+    private bool DetermineHarborPresence(Settlement settlement)
+    {
+        if (mapData == null) return false;
+
+        // Check nearby tiles for water
+        for (int dx = -2; dx <= 2; dx++)
+        {
+            for (int dy = -2; dy <= 2; dy++)
+            {
+                int checkX = settlement.position.x + dx;
+                int checkY = settlement.position.y + dy;
+
+                var tile = mapData.GetTile(checkX, checkY);
+                if (tile != null && (tile.terrainType == TerrainType.Ocean || tile.terrainType == TerrainType.Lake || tile.terrainType == TerrainType.River))
+                {
+                    return true;
+                }
+            }
+        }
+
+        return false;
+    }
+
+    /// <summary>
+    /// Setup SettlementContext for scene transition
+    /// </summary>
+    private void SetupSettlementContext(Settlement settlement, bool hasHarbor)
+    {
+        // Find or create SettlementContext
+        var existingContext = FindFirstObjectByType<SettlementContext>();
+        SettlementContext context;
+
+        if (existingContext != null)
+        {
+            context = existingContext;
+        }
+        else
+        {
+            var contextObject = new GameObject("SettlementContext");
+            context = contextObject.AddComponent<SettlementContext>();
+            DontDestroyOnLoad(contextObject);
+        }
+
+        // Set settlement data
+        context.SetSettlement(settlement.name, settlement.Type, settlement.position, hasHarbor);
+
+        LogDebug($"SettlementContext configured: {settlement.name} ({settlement.Type}) - Harbor: {hasHarbor}");
+    }
+
+    /// <summary>
+    /// Load the town scene
+    /// </summary>
+    private void LoadTownScene()
+    {
+        LogDebug($"Loading town scene: {townSceneName}");
+        SceneManager.LoadScene(townSceneName);
+    }
+
+    /// <summary>
+    /// Update UI based on current settlement state
+    /// </summary>
+    private void UpdateUI()
+    {
+        if (interactionPrompt == null) return;
+
+        if (currentNearbySettlement != null)
+        {
+            interactionPrompt.SetActive(true);
+            // You could update text here to show settlement name and interaction key
+        }
+        else
+        {
+            interactionPrompt.SetActive(false);
+        }
+    }
+
+    /// <summary>
+    /// Log debug message if debug logging is enabled
+    /// </summary>
+    private void LogDebug(string message)
+    {
+        if (enableDebugLogs)
+        {
+            Debug.Log($"[SettlementInteraction] {message}");
+        }
+    }
+
+    /// <summary>
+    /// Force enter a settlement by name (for testing)
+    /// </summary>
+    [ContextMenu("Test Enter Current Settlement")]
+    public void TestEnterCurrentSettlement()
+    {
+        if (currentNearbySettlement != null)
+        {
+            EnterSettlement(currentNearbySettlement);
+        }
+        else
+        {
+            LogDebug("No settlement nearby to enter");
+        }
+    }
+
+    /// <summary>
+    /// Get current nearby settlement (for external scripts)
+    /// </summary>
+    public Settlement GetCurrentNearbySettlement()
+    {
+        return currentNearbySettlement;
+    }
+
+    /// <summary>
+    /// Manually set team marker reference (for external scripts)
+    /// </summary>
+    public void SetTeamMarker(Transform marker)
+    {
+        teamMarker = marker;
+        if (marker != null)
+        {
+            lastTeamMarkerPosition = marker.position;
+            LogDebug("Team marker reference updated");
+        }
+    }
+}

+ 12 - 0
Assets/Scripts/Map/SimpleTeamPlacement.cs

@@ -244,6 +244,18 @@ public class SimpleTeamPlacement : MonoBehaviour
         if (mapMaker != null)
         {
             mapMaker.OnTeamPositionChanged(position);
+
+            // Set TeamMarker reference in SettlementInteractionManager
+            var settlementManager = FindFirstObjectByType<SettlementInteractionManager>();
+            if (settlementManager != null)
+            {
+                settlementManager.SetTeamMarker(teamMarkerInstance.transform);
+                Debug.Log($"[SimpleTeamPlacement] Set TeamMarker reference in SettlementInteractionManager");
+            }
+            else
+            {
+                Debug.LogWarning("[SimpleTeamPlacement] SettlementInteractionManager not found!");
+            }
         }
 
     }

+ 10 - 0
Assets/Scripts/MapMaker2/Data/MapData.cs

@@ -139,6 +139,16 @@ public class MapData
         return settlements.Where(s => s.Type == SettlementType.Village).ToList();
     }
 
+    public List<Settlement> GetAllSettlements()
+    {
+        return new List<Settlement>(settlements);
+    }
+
+    public Settlement GetSettlementAt(Vector2Int position, float tolerance = 1f)
+    {
+        return settlements.FirstOrDefault(s => Vector2Int.Distance(s.position, position) <= tolerance);
+    }
+
     public List<Vector2Int> GetNeighbors(int x, int y, bool includeDiagonals = false)
     {
         List<Vector2Int> neighbors = new List<Vector2Int>();

+ 228 - 0
Assets/Scripts/Town/ItemCreatorHelper.cs

@@ -0,0 +1,228 @@
+using UnityEngine;
+
+#if UNITY_EDITOR
+using UnityEditor;
+
+public class ItemCreatorHelper
+{
+    [MenuItem("RPG Tools/Create Sample Items")]
+    public static void CreateSampleItems()
+    {
+        CreateSampleWeapons();
+        CreateSampleArmor();
+        CreateSampleConsumables();
+        CreateSampleMiscItems();
+
+        AssetDatabase.SaveAssets();
+        AssetDatabase.Refresh();
+
+        Debug.Log("Sample items created successfully!");
+    }
+
+    private static void CreateSampleWeapons()
+    {
+        EnsureFolderExists("Assets/Resources/Items/Weapons");
+
+        // Simple Sword
+        var simpleSword = ScriptableObject.CreateInstance<WeaponItem>();
+        simpleSword.itemName = "Simple Sword";
+        simpleSword.description = "A basic iron blade, reliable and sturdy";
+        simpleSword.goldCost = 15;
+        simpleSword.silverCost = 0;
+        simpleSword.copperCost = 0;
+        simpleSword.itemType = ItemType.Weapon;
+        simpleSword.rarity = ItemRarity.Common;
+        simpleSword.weaponType = WeaponType.Sword;
+        simpleSword.weaponClassName = "SimpleSword";
+        simpleSword.minDamage = 4;
+        simpleSword.maxDamage = 8;
+        simpleSword.searchTags = new string[] { "melee", "blade", "sword", "iron" };
+        AssetDatabase.CreateAsset(simpleSword, "Assets/Resources/Items/Weapons/SimpleSword.asset");
+
+        // War Axe
+        var warAxe = ScriptableObject.CreateInstance<WeaponItem>();
+        warAxe.itemName = "War Axe";
+        warAxe.description = "A heavy two-handed axe that cleaves through armor";
+        warAxe.goldCost = 22;
+        warAxe.itemType = ItemType.Weapon;
+        warAxe.rarity = ItemRarity.Common;
+        warAxe.weaponType = WeaponType.Axe;
+        warAxe.weaponClassName = "SimpleSword"; // Reuse for now
+        warAxe.minDamage = 6;
+        warAxe.maxDamage = 12;
+        warAxe.searchTags = new string[] { "melee", "axe", "two-handed", "heavy" };
+        AssetDatabase.CreateAsset(warAxe, "Assets/Resources/Items/Weapons/WarAxe.asset");
+
+        // Hunting Bow
+        var huntingBow = ScriptableObject.CreateInstance<WeaponItem>();
+        huntingBow.itemName = "Hunting Bow";
+        huntingBow.description = "A reliable ranged weapon favored by hunters";
+        huntingBow.goldCost = 18;
+        huntingBow.itemType = ItemType.Weapon;
+        huntingBow.rarity = ItemRarity.Common;
+        huntingBow.weaponType = WeaponType.Bow;
+        huntingBow.weaponClassName = "SimpleBow";
+        huntingBow.minDamage = 3;
+        huntingBow.maxDamage = 6;
+        huntingBow.range = 30;
+        huntingBow.searchTags = new string[] { "ranged", "bow", "hunting", "arrows" };
+        AssetDatabase.CreateAsset(huntingBow, "Assets/Resources/Items/Weapons/HuntingBow.asset");
+
+        // Iron Dagger
+        var ironDagger = ScriptableObject.CreateInstance<WeaponItem>();
+        ironDagger.itemName = "Iron Dagger";
+        ironDagger.description = "Quick and light, perfect for swift strikes";
+        ironDagger.goldCost = 8;
+        ironDagger.itemType = ItemType.Weapon;
+        ironDagger.rarity = ItemRarity.Common;
+        ironDagger.weaponType = WeaponType.Dagger;
+        ironDagger.weaponClassName = "SimpleSword"; // Reuse for now
+        ironDagger.minDamage = 2;
+        ironDagger.maxDamage = 5;
+        ironDagger.searchTags = new string[] { "melee", "dagger", "quick", "light", "iron" };
+        AssetDatabase.CreateAsset(ironDagger, "Assets/Resources/Items/Weapons/IronDagger.asset");
+    }
+
+    private static void CreateSampleArmor()
+    {
+        EnsureFolderExists("Assets/Resources/Items/Armor");
+
+        // Leather Vest
+        var leatherVest = ScriptableObject.CreateInstance<ArmorItem>();
+        leatherVest.itemName = "Leather Vest";
+        leatherVest.description = "Light chest protection made from quality leather";
+        leatherVest.goldCost = 10;
+        leatherVest.itemType = ItemType.Armor;
+        leatherVest.rarity = ItemRarity.Common;
+        leatherVest.armorType = ArmorType.Light;
+        leatherVest.armorSlot = ArmorSlot.Chest;
+        leatherVest.armorClass = 2;
+        leatherVest.searchTags = new string[] { "light", "leather", "chest", "vest" };
+        AssetDatabase.CreateAsset(leatherVest, "Assets/Resources/Items/Armor/LeatherVest.asset");
+
+        // Iron Helmet
+        var ironHelmet = ScriptableObject.CreateInstance<ArmorItem>();
+        ironHelmet.itemName = "Iron Helmet";
+        ironHelmet.description = "Sturdy head protection forged from iron";
+        ironHelmet.goldCost = 15;
+        ironHelmet.itemType = ItemType.Armor;
+        ironHelmet.rarity = ItemRarity.Common;
+        ironHelmet.armorType = ArmorType.Medium;
+        ironHelmet.armorSlot = ArmorSlot.Head;
+        ironHelmet.armorClass = 3;
+        ironHelmet.searchTags = new string[] { "medium", "iron", "head", "helmet" };
+        AssetDatabase.CreateAsset(ironHelmet, "Assets/Resources/Items/Armor/IronHelmet.asset");
+
+        // Chainmail Shirt
+        var chainmail = ScriptableObject.CreateInstance<ArmorItem>();
+        chainmail.itemName = "Chainmail Shirt";
+        chainmail.description = "Interlocked metal rings provide excellent protection";
+        chainmail.goldCost = 35;
+        chainmail.itemType = ItemType.Armor;
+        chainmail.rarity = ItemRarity.Uncommon;
+        chainmail.armorType = ArmorType.Medium;
+        chainmail.armorSlot = ArmorSlot.Chest;
+        chainmail.armorClass = 5;
+        chainmail.searchTags = new string[] { "medium", "chainmail", "chest", "metal" };
+        AssetDatabase.CreateAsset(chainmail, "Assets/Resources/Items/Armor/ChainmailShirt.asset");
+    }
+
+    private static void CreateSampleConsumables()
+    {
+        EnsureFolderExists("Assets/Resources/Items/Miscellaneous");
+
+        // Health Potion
+        var healthPotion = ScriptableObject.CreateInstance<MiscellaneousItem>();
+        healthPotion.itemName = "Health Potion";
+        healthPotion.description = "A red liquid that restores 25 health points";
+        healthPotion.goldCost = 5;
+        healthPotion.itemType = ItemType.Consumable;
+        healthPotion.rarity = ItemRarity.Common;
+        healthPotion.isConsumable = true;
+        healthPotion.searchTags = new string[] { "potion", "healing", "health", "red" };
+        AssetDatabase.CreateAsset(healthPotion, "Assets/Resources/Items/Miscellaneous/HealthPotion.asset");
+
+        // Mana Potion
+        var manaPotion = ScriptableObject.CreateInstance<MiscellaneousItem>();
+        manaPotion.itemName = "Mana Potion";
+        manaPotion.description = "A blue elixir that restores 15 mana points";
+        manaPotion.goldCost = 7;
+        manaPotion.itemType = ItemType.Consumable;
+        manaPotion.rarity = ItemRarity.Common;
+        manaPotion.isConsumable = true;
+        manaPotion.searchTags = new string[] { "potion", "mana", "magic", "blue" };
+        AssetDatabase.CreateAsset(manaPotion, "Assets/Resources/Items/Miscellaneous/ManaPotion.asset");
+
+        // Antidote
+        var antidote = ScriptableObject.CreateInstance<MiscellaneousItem>();
+        antidote.itemName = "Antidote";
+        antidote.description = "Neutralizes most common poisons";
+        antidote.goldCost = 3;
+        antidote.itemType = ItemType.Consumable;
+        antidote.rarity = ItemRarity.Common;
+        antidote.isConsumable = true;
+        antidote.searchTags = new string[] { "antidote", "poison", "cure", "healing" };
+        AssetDatabase.CreateAsset(antidote, "Assets/Resources/Items/Miscellaneous/Antidote.asset");
+    }
+
+    private static void CreateSampleMiscItems()
+    {
+        EnsureFolderExists("Assets/Resources/Items/Miscellaneous");
+
+        // Hemp Rope
+        var rope = ScriptableObject.CreateInstance<MiscellaneousItem>();
+        rope.itemName = "Hemp Rope";
+        rope.description = "50 feet of sturdy rope, useful for climbing";
+        rope.goldCost = 2;
+        rope.itemType = ItemType.Tool;
+        rope.rarity = ItemRarity.Common;
+        rope.isConsumable = false;
+        rope.searchTags = new string[] { "rope", "climbing", "tool", "hemp" };
+        AssetDatabase.CreateAsset(rope, "Assets/Resources/Items/Miscellaneous/HempRope.asset");
+
+        // Torch
+        var torch = ScriptableObject.CreateInstance<MiscellaneousItem>();
+        torch.itemName = "Torch";
+        torch.description = "Provides light in dark places";
+        torch.goldCost = 0;
+        torch.silverCost = 5;
+        torch.itemType = ItemType.Tool;
+        torch.rarity = ItemRarity.Common;
+        torch.isConsumable = true;
+        torch.searchTags = new string[] { "torch", "light", "fire", "tool" };
+        AssetDatabase.CreateAsset(torch, "Assets/Resources/Items/Miscellaneous/Torch.asset");
+
+        // Lockpicks
+        var lockpicks = ScriptableObject.CreateInstance<MiscellaneousItem>();
+        lockpicks.itemName = "Lockpicks";
+        lockpicks.description = "Fine tools for opening locks";
+        lockpicks.goldCost = 8;
+        lockpicks.itemType = ItemType.Tool;
+        lockpicks.rarity = ItemRarity.Common;
+        lockpicks.isConsumable = false;
+        lockpicks.searchTags = new string[] { "lockpicks", "tools", "thief", "locks" };
+        AssetDatabase.CreateAsset(lockpicks, "Assets/Resources/Items/Miscellaneous/Lockpicks.asset");
+
+        // Camping Kit
+        var campingKit = ScriptableObject.CreateInstance<MiscellaneousItem>();
+        campingKit.itemName = "Camping Kit";
+        campingKit.description = "Everything needed for a comfortable night outdoors";
+        campingKit.goldCost = 15;
+        campingKit.itemType = ItemType.Tool;
+        campingKit.rarity = ItemRarity.Common;
+        campingKit.isConsumable = false;
+        campingKit.searchTags = new string[] { "camping", "rest", "outdoor", "kit" };
+        AssetDatabase.CreateAsset(campingKit, "Assets/Resources/Items/Miscellaneous/CampingKit.asset");
+    }
+
+    private static void EnsureFolderExists(string path)
+    {
+        if (!AssetDatabase.IsValidFolder(path))
+        {
+            var parentPath = System.IO.Path.GetDirectoryName(path);
+            var folderName = System.IO.Path.GetFileName(path);
+            AssetDatabase.CreateFolder(parentPath, folderName);
+        }
+    }
+}
+#endif

+ 150 - 0
Assets/Scripts/Town/SettlementContext.cs

@@ -0,0 +1,150 @@
+using UnityEngine;
+
+/// <summary>
+/// Singleton that persists settlement data across scene transitions
+/// Ensures town generation is consistent based on settlement type
+/// </summary>
+public class SettlementContext : MonoBehaviour
+{
+    public static SettlementContext Instance { get; private set; }
+
+    [Header("Current Settlement Data")]
+    public string settlementName = "Haven Village";
+    public SettlementType settlementType = SettlementType.Town;
+    public bool hasHarbor = false;
+    public Vector2Int mapPosition = Vector2Int.zero;
+    public int settlementSeed = 0; // For consistent generation
+
+    [Header("Generated Data")]
+    public TownShop[] availableShops;
+    public ShopData[] generatedShopData; // Data-only shop definitions
+    public bool isGenerated = false;
+
+    private void Awake()
+    {
+        // Singleton pattern - persist across scenes
+        if (Instance == null)
+        {
+            Instance = this;
+            DontDestroyOnLoad(gameObject);
+            Debug.Log("SettlementContext created and marked as DontDestroyOnLoad");
+        }
+        else
+        {
+            Debug.Log("SettlementContext already exists, destroying duplicate");
+            Destroy(gameObject);
+        }
+    }
+
+    /// <summary>
+    /// Set settlement data before entering town scene
+    /// </summary>
+    public void SetSettlement(string name, SettlementType type, Vector2Int position, bool harbor = false)
+    {
+        settlementName = name;
+        settlementType = type;
+        mapPosition = position;
+        hasHarbor = harbor;
+
+        // Generate consistent seed based on position and name
+        settlementSeed = (position.x * 1000 + position.y) ^ name.GetHashCode();
+
+        // Clear existing generation to force regeneration
+        isGenerated = false;
+        availableShops = null;
+
+        Debug.Log($"Settlement context set: {name} ({type}) at {position}, seed: {settlementSeed}");
+    }
+
+    /// <summary>
+    /// <summary>
+    /// Generate shops based on settlement type - just logs what would be created
+    /// TownShopManager handles the actual shop configuration
+    /// </summary>
+    public TownShop[] GenerateShops()
+    {
+        if (isGenerated)
+        {
+            Debug.Log("Settlement already generated");
+            return new TownShop[0];
+        }
+
+        Debug.Log($"Planning shops for {settlementType}: {settlementName}");
+
+        // Use settlement seed for consistent generation logging
+        var oldState = Random.state;
+        Random.InitState(settlementSeed);
+
+        if (settlementType == SettlementType.Town)
+        {
+            Debug.Log("Town will have: Weapons, Armor, Potions, General shops");
+            if (Random.value > 0.3f) // 70% chance
+            {
+                Debug.Log("Town will also have: Adventurer's Guild");
+            }
+            if (hasHarbor && Random.value > 0.5f) // 50% chance if near water
+            {
+                Debug.Log("Town will also have: Harbor Trading Post");
+            }
+        }
+        else // Village
+        {
+            Debug.Log("Village will have: General Store");
+            if (Random.value > 0.4f) // 60% chance
+            {
+                var shopTypes = new string[] { "Herb Shop", "Old Weaponsmith" };
+                int index = Random.Range(0, shopTypes.Length);
+                Debug.Log($"Village will also have: {shopTypes[index]}");
+            }
+        }
+
+        // Restore random state
+        Random.state = oldState;
+        isGenerated = true;
+
+        Debug.Log("Shop configuration complete - TownShopManager will handle activation");
+        return new TownShop[0]; // No MonoBehaviour instances created here
+    }
+
+    /// <summary>
+    /// Get shops for current settlement (generates if needed)
+    /// </summary>
+    public TownShop[] GetShops()
+    {
+        if (!isGenerated || availableShops == null)
+        {
+            return GenerateShops();
+        }
+        return availableShops;
+    }
+
+    /// <summary>
+    /// Clear settlement data (for testing)
+    /// </summary>
+    [ContextMenu("Clear Settlement Data")]
+    public void ClearSettlementData()
+    {
+        isGenerated = false;
+        availableShops = null;
+        Debug.Log("Settlement data cleared");
+    }
+
+    /// <summary>
+    /// Debug method to test different settlement types
+    /// </summary>
+    [ContextMenu("Test Village Generation")]
+    public void TestVillageGeneration()
+    {
+        SetSettlement("Test Village", SettlementType.Village, new Vector2Int(50, 50));
+        var shops = GenerateShops();
+        Debug.Log($"Village shops: {string.Join(", ", System.Array.ConvertAll(shops, s => s.buildingName))}");
+    }
+
+    [ContextMenu("Test Town Generation")]
+    public void TestTownGeneration()
+    {
+        SetSettlement("Test Town", SettlementType.Town, new Vector2Int(100, 100), true);
+        var shops = GenerateShops();
+        Debug.Log($"Town shops: {string.Join(", ", System.Array.ConvertAll(shops, s => s.buildingName))}");
+    }
+}

+ 131 - 0
Assets/Scripts/Town/SettlementTestHelper.cs

@@ -0,0 +1,131 @@
+using UnityEngine;
+
+/// <summary>
+/// Test helper to simulate entering different settlement types
+/// Use this to test town vs village generation
+/// </summary>
+public class SettlementTestHelper : MonoBehaviour
+{
+    [Header("Test Controls")]
+    public bool createContextOnStart = false; // DISABLED - Don't override real settlement context
+    public SettlementType testSettlementType = SettlementType.Town;
+    public string testSettlementName = "Test Town";
+    public bool testHasHarbor = false;
+
+    void Start()
+    {
+        // COMPLETELY DISABLED - This component should never interfere with real settlement system
+        Debug.Log("SettlementTestHelper: DISABLED - No test context creation allowed");
+        return;
+
+        if (createContextOnStart)
+        {
+            Debug.Log("SettlementTestHelper: Creating test context (should only happen during testing)");
+            CreateTestSettlementContext();
+        }
+        else
+        {
+            Debug.Log("SettlementTestHelper: Disabled - not creating test context");
+        }
+    }
+
+    [ContextMenu("Create Test Town Context")]
+    public void CreateTestTownContext()
+    {
+        CreateSettlementContext("Test Town", SettlementType.Town, new Vector2Int(100, 100), true);
+    }
+
+    [ContextMenu("Create Test Village Context")]
+    public void CreateTestVillageContext()
+    {
+        CreateSettlementContext("Test Village", SettlementType.Village, new Vector2Int(50, 50), false);
+    }
+
+    [ContextMenu("Create Custom Test Context")]
+    public void CreateTestSettlementContext()
+    {
+        CreateSettlementContext(testSettlementName, testSettlementType, new Vector2Int(75, 75), testHasHarbor);
+    }
+
+    private void CreateSettlementContext(string name, SettlementType type, Vector2Int position, bool harbor)
+    {
+        // Find or create SettlementContext
+        var existingContext = FindFirstObjectByType<SettlementContext>();
+        SettlementContext context;
+
+        if (existingContext != null)
+        {
+            context = existingContext;
+            Debug.Log("Using existing SettlementContext");
+        }
+        else
+        {
+            var contextObject = new GameObject("SettlementContext");
+            context = contextObject.AddComponent<SettlementContext>();
+            Debug.Log("Created new SettlementContext");
+        }
+
+        // Set settlement data
+        context.SetSettlement(name, type, position, harbor);
+
+        Debug.Log($"✅ Settlement context configured: {name} ({type}) - Harbor: {harbor}");
+
+        // Force regenerate shops to see immediate effect
+        var shops = context.GenerateShops();
+        Debug.Log($"Generated shops: {string.Join(", ", System.Array.ConvertAll(shops, s => s.buildingName))}");
+
+        // Update any existing TownShopManager
+        var shopManager = FindFirstObjectByType<TownShopManager>();
+        if (shopManager != null)
+        {
+            Debug.Log("Forcing TownShopManager to reinitialize with new settlement data");
+            // Force clear the shops and reinitialize everything properly
+            shopManager.allShops = null;
+            shopManager.ReinitializeShopsAndUI(); // Use the new method that handles UI properly
+        }
+
+        // Update TownManager if it exists
+        var townManager = FindFirstObjectByType<TownManager>();
+        if (townManager != null)
+        {
+            townManager.townName = name;
+            townManager.hasHarbor = harbor;
+            Debug.Log("Updated TownManager with settlement data");
+        }
+    }
+
+    [ContextMenu("Clear Settlement Context")]
+    public void ClearSettlementContext()
+    {
+        var context = FindFirstObjectByType<SettlementContext>();
+        if (context != null)
+        {
+            context.ClearSettlementData();
+            Debug.Log("Settlement context cleared");
+        }
+        else
+        {
+            Debug.Log("No settlement context found to clear");
+        }
+    }
+
+    [ContextMenu("Print Current Context")]
+    public void PrintCurrentContext()
+    {
+        if (SettlementContext.Instance != null)
+        {
+            var ctx = SettlementContext.Instance;
+            Debug.Log($"Current Settlement Context:");
+            Debug.Log($"  Name: {ctx.settlementName}");
+            Debug.Log($"  Type: {ctx.settlementType}");
+            Debug.Log($"  Position: {ctx.mapPosition}");
+            Debug.Log($"  Harbor: {ctx.hasHarbor}");
+            Debug.Log($"  Generated: {ctx.isGenerated}");
+            Debug.Log($"  Shop Count: {(ctx.availableShops?.Length ?? 0)}");
+        }
+        else
+        {
+            Debug.Log("No SettlementContext instance found");
+        }
+    }
+}

+ 45 - 0
Assets/Scripts/Town/ShopData.cs

@@ -0,0 +1,45 @@
+using UnityEngine;
+using System.Collections.Generic;
+
+/// <summary>
+/// Data-only structure for shop generation (not a MonoBehaviour)
+/// Used by SettlementContext to define shop properties
+/// </summary>
+[System.Serializable]
+public class ShopData
+{
+    public string buildingName;
+    public ShopType shopType;
+    public string shopkeeperName;
+    public Vector2Int gridPosition;
+    public Color buildingColor;
+    public bool isAvailable;
+
+    public ShopData(string name, ShopType type, string keeper, Vector2Int position, Color color)
+    {
+        buildingName = name;
+        shopType = type;
+        shopkeeperName = keeper;
+        gridPosition = position;
+        buildingColor = color;
+        isAvailable = true;
+    }
+
+    /// <summary>
+    /// Convert this ShopData to a TownShop component on the given GameObject
+    /// </summary>
+    public TownShop ApplyToTownShop(GameObject shopObject)
+    {
+        var townShop = shopObject.GetComponent<TownShop>();
+        if (townShop == null)
+            townShop = shopObject.AddComponent<TownShop>();
+
+        townShop.buildingName = buildingName;
+        townShop.shopType = shopType;
+        townShop.shopkeeperName = shopkeeperName;
+        townShop.gridPosition = gridPosition;
+        townShop.buildingColor = buildingColor;
+
+        return townShop;
+    }
+}

+ 103 - 0
Assets/Scripts/Town/ShopNameGenerator.cs

@@ -0,0 +1,103 @@
+using UnityEngine;
+using System.Collections.Generic;
+
+/// <summary>
+/// Generates randomized shop names based on shop type and settlement seed
+/// </summary>
+public static class ShopNameGenerator
+{
+    private static readonly Dictionary<ShopType, (string[] prefixes, string[] suffixes)> shopNameParts =
+        new Dictionary<ShopType, (string[], string[])>
+        {
+            [ShopType.Weapons] = (
+            new string[] { "Iron", "Steel", "Sharp", "Blade", "Sword", "Battle", "War", "Forge", "Smith's", "Master" },
+            new string[] { "Forge", "Armory", "Smithy", "Workshop", "Arms", "Weapons", "Blades", "Steel", "Works", "Arsenal" }
+        ),
+            [ShopType.Armor] = (
+            new string[] { "Iron", "Steel", "Shield", "Guard", "Protection", "Battle", "Sturdy", "Strong", "Heavy", "Knight's" },
+            new string[] { "Armory", "Protection", "Guards", "Shields", "Armor", "Defense", "Gear", "Works", "Smithy", "Hall" }
+        ),
+            [ShopType.Potions] = (
+            new string[] { "Mystic", "Magic", "Healing", "Wise", "Ancient", "Bubbling", "Crystal", "Elven", "Herbal", "Sacred" },
+            new string[] { "Potions", "Elixirs", "Brews", "Cauldron", "Remedies", "Apothecary", "Alchemy", "Lab", "Herbs", "Tonics" }
+        ),
+            [ShopType.General] = (
+            new string[] { "General", "Trading", "Merchant's", "Common", "Useful", "Daily", "Town", "Village", "Traveler's", "Wanderer's" },
+            new string[] { "Goods", "Store", "Supplies", "Trading Post", "Emporium", "Market", "Shop", "Merchant", "General Store", "Bazaar" }
+        ),
+            [ShopType.Magic] = (
+            new string[] { "Arcane", "Mystical", "Enchanted", "Magical", "Wizard's", "Sorcerer's", "Ancient", "Ethereal", "Divine", "Celestial" },
+            new string[] { "Emporium", "Artifacts", "Relics", "Magic", "Enchantments", "Scrolls", "Tomes", "Mysteries", "Wonders", "Sanctum" }
+        ),
+            [ShopType.Tools] = (
+            new string[] { "Useful", "Handy", "Crafting", "Builder's", "Worker's", "Master", "Quality", "Fine", "Reliable", "Sturdy" },
+            new string[] { "Tools", "Implements", "Workshop", "Supplies", "Equipment", "Gear", "Utilities", "Hardware", "Crafts", "Works" }
+        )
+        };
+
+    private static readonly string[] keepersNameParts = new string[]
+    {
+        // Male names
+        "Marcus", "Gareth", "Thorin", "Finn", "Aldric", "Bram", "Cael", "Daven", "Erik", "Galen",
+        "Hector", "Ivan", "Joren", "Kane", "Lars", "Magnus", "Nolan", "Owen", "Pike", "Quinn",
+        
+        // Female names  
+        "Elara", "Brenna", "Cira", "Delia", "Evelyn", "Fiona", "Greta", "Hilda", "Iris", "Jenna",
+        "Kira", "Luna", "Mira", "Nina", "Olivia", "Piper", "Rose", "Sara", "Tara", "Vera",
+        
+        // Fantasy names
+        "Zephyr", "Xara", "Vex", "Wick", "Yara", "Zane"
+    };
+
+    /// <summary>
+    /// Generate a randomized shop name based on shop type and seed
+    /// </summary>
+    public static string GenerateShopName(ShopType shopType, int seed)
+    {
+        var random = new System.Random(seed);
+
+        if (!shopNameParts.ContainsKey(shopType))
+        {
+            return $"Unknown {shopType} Shop";
+        }
+
+        var parts = shopNameParts[shopType];
+        var prefix = parts.prefixes[random.Next(parts.prefixes.Length)];
+        var suffix = parts.suffixes[random.Next(parts.suffixes.Length)];
+
+        // Sometimes use "The" prefix
+        var useThe = random.NextDouble() > 0.6;
+        var shopName = useThe ? $"The {prefix} {suffix}" : $"{prefix} {suffix}";
+
+        return shopName;
+    }
+
+    /// <summary>
+    /// Generate a randomized shopkeeper name based on seed
+    /// </summary>
+    public static string GenerateShopkeeperName(int seed)
+    {
+        var random = new System.Random(seed);
+        return keepersNameParts[random.Next(keepersNameParts.Length)];
+    }
+
+    /// <summary>
+    /// Generate a shop name with embedded settlement and shop type info for uniqueness
+    /// </summary>
+    public static string GenerateUniqueShopName(ShopType shopType, string settlementName, Vector2Int position)
+    {
+        // Create a unique seed based on settlement name, position, and shop type
+        var combinedSeed = settlementName.GetHashCode() ^ position.GetHashCode() ^ shopType.GetHashCode();
+        return GenerateShopName(shopType, combinedSeed);
+    }
+
+    /// <summary>
+    /// Generate a shopkeeper name with embedded settlement and shop type info for uniqueness
+    /// </summary>
+    public static string GenerateUniqueShopkeeperName(ShopType shopType, string settlementName, Vector2Int position)
+    {
+        // Create a unique seed based on settlement name, position, and shop type (offset for different result)
+        var combinedSeed = (settlementName.GetHashCode() ^ position.GetHashCode() ^ shopType.GetHashCode()) + 12345;
+        return GenerateShopkeeperName(combinedSeed);
+    }
+}

+ 131 - 0
Assets/Scripts/Town/SimpleTownShopUI.cs

@@ -0,0 +1,131 @@
+using UnityEngine;
+using UnityEngine.UIElements;
+using System.Collections.Generic;
+using System.Linq;
+using System;
+
+public class SimpleTownShopUI : MonoBehaviour
+{
+    private TownShop currentShop;
+    private TeamCharacter[] currentTeam;
+    private Action onCloseCallback;
+
+    public void OpenShop(TownShop shop, TeamCharacter[] team, Action closeCallback)
+    {
+        currentShop = shop;
+        currentTeam = team;
+        onCloseCallback = closeCallback;
+
+        Debug.Log($"Opening {shop.buildingName} - This is a simplified shop UI for testing");
+        CreateSimpleUI();
+    }
+
+    private void CreateSimpleUI()
+    {
+        // Create UI Document
+        var uiDocument = gameObject.AddComponent<UIDocument>();
+
+        // Create a simple overlay UI
+        var root = new VisualElement();
+        root.style.width = Length.Percent(100);
+        root.style.height = Length.Percent(100);
+        root.style.position = Position.Absolute;
+        root.style.backgroundColor = new Color(0, 0, 0, 0.8f);
+        root.style.justifyContent = Justify.Center;
+        root.style.alignItems = Align.Center;
+
+        // Create shop dialog
+        var dialog = new VisualElement();
+        dialog.style.width = 400;
+        dialog.style.height = 300;
+        dialog.style.backgroundColor = new Color(0.2f, 0.15f, 0.1f, 1f);
+        dialog.style.borderTopWidth = 3;
+        dialog.style.borderBottomWidth = 3;
+        dialog.style.borderLeftWidth = 3;
+        dialog.style.borderRightWidth = 3;
+        dialog.style.borderTopColor = new Color(0.8f, 0.6f, 0.2f, 1f);
+        dialog.style.borderBottomColor = new Color(0.8f, 0.6f, 0.2f, 1f);
+        dialog.style.borderLeftColor = new Color(0.8f, 0.6f, 0.2f, 1f);
+        dialog.style.borderRightColor = new Color(0.8f, 0.6f, 0.2f, 1f);
+        dialog.style.paddingTop = 20;
+        dialog.style.paddingBottom = 20;
+        dialog.style.paddingLeft = 20;
+        dialog.style.paddingRight = 20;
+        dialog.style.justifyContent = Justify.SpaceBetween;
+
+        // Title
+        var title = new Label(currentShop.buildingName);
+        title.style.fontSize = 24;
+        title.style.color = new Color(1f, 0.84f, 0f, 1f);
+        title.style.unityFontStyleAndWeight = FontStyle.Bold;
+        title.style.unityTextAlign = TextAnchor.MiddleCenter;
+
+        // Content
+        var content = new VisualElement();
+        content.style.flexGrow = 1;
+        content.style.justifyContent = Justify.Center;
+
+        var welcomeText = new Label($"Welcome to {currentShop.buildingName}!");
+        welcomeText.style.color = Color.white;
+        welcomeText.style.fontSize = 16;
+        welcomeText.style.unityTextAlign = TextAnchor.MiddleCenter;
+        welcomeText.style.marginBottom = 10;
+
+        var inventoryText = new Label($"Items in stock: {currentShop.currentInventory.Count}");
+        inventoryText.style.color = Color.white;
+        inventoryText.style.fontSize = 14;
+        inventoryText.style.unityTextAlign = TextAnchor.MiddleCenter;
+        inventoryText.style.marginBottom = 10;
+
+        var playerMoney = "";
+        if (currentTeam != null && currentTeam.Length > 0)
+        {
+            var player = currentTeam[0];
+            playerMoney = $"Your money: {player.gold}g {player.silver}s {player.copper}c";
+        }
+        else
+        {
+            playerMoney = "Your money: 100g 50s 25c";
+        }
+
+        var moneyText = new Label(playerMoney);
+        moneyText.style.color = new Color(1f, 0.84f, 0f, 1f);
+        moneyText.style.fontSize = 14;
+        moneyText.style.unityTextAlign = TextAnchor.MiddleCenter;
+        moneyText.style.marginBottom = 20;
+
+        var noteText = new Label("(This is a simplified shop UI for testing.\nFull shop functionality will be added later.)");
+        noteText.style.color = new Color(0.8f, 0.8f, 0.8f, 1f);
+        noteText.style.fontSize = 12;
+        noteText.style.unityTextAlign = TextAnchor.MiddleCenter;
+
+        content.Add(welcomeText);
+        content.Add(inventoryText);
+        content.Add(moneyText);
+        content.Add(noteText);
+
+        // Close button
+        var closeButton = new Button(() => CloseShop()) { text = "Close Shop" };
+        closeButton.style.backgroundColor = new Color(0.7f, 0.2f, 0.2f, 1f);
+        closeButton.style.color = Color.white;
+        closeButton.style.paddingTop = 10;
+        closeButton.style.paddingBottom = 10;
+        closeButton.style.fontSize = 16;
+
+        dialog.Add(title);
+        dialog.Add(content);
+        dialog.Add(closeButton);
+
+        root.Add(dialog);
+        uiDocument.rootVisualElement.Clear();
+        uiDocument.rootVisualElement.Add(root);
+
+        Debug.Log("Simple shop UI created and displayed!");
+    }
+
+    private void CloseShop()
+    {
+        Debug.Log($"Closing {currentShop.buildingName}");
+        onCloseCallback?.Invoke();
+    }
+}

+ 44 - 0
Assets/Scripts/Town/TestTownShopUI.cs

@@ -0,0 +1,44 @@
+using UnityEngine;
+using UnityEngine.UIElements;
+
+public class TestTownShopUI : MonoBehaviour
+{
+    public void TestShopUI()
+    {
+        Debug.Log("Creating test shop UI...");
+
+        var shopUIObject = new GameObject("TestTownShopUI");
+        var uiDocument = shopUIObject.AddComponent<UIDocument>();
+
+        // Load the UXML
+        uiDocument.visualTreeAsset = Resources.Load<VisualTreeAsset>("UI/TownShopUI");
+
+        if (uiDocument.visualTreeAsset == null)
+        {
+            Debug.LogError("Failed to load UXML!");
+            return;
+        }
+
+        Debug.Log("UXML loaded successfully");
+
+        // Get the root and shop container
+        var root = uiDocument.rootVisualElement;
+        var shopContainer = root?.Q<VisualElement>("shop-container");
+
+        Debug.Log($"Root: {root != null}, ShopContainer: {shopContainer != null}");
+
+        if (shopContainer != null)
+        {
+            shopContainer.style.display = DisplayStyle.Flex;
+            Debug.Log("Shop container made visible");
+
+            // Test setting some content
+            var shopName = root.Q<Label>("shop-name");
+            if (shopName != null)
+            {
+                shopName.text = "TEST SHOP";
+                Debug.Log("Shop name set");
+            }
+        }
+    }
+}

+ 94 - 0
Assets/Scripts/Town/TownBuilding.cs

@@ -0,0 +1,94 @@
+using UnityEngine;
+using UnityEngine.UIElements;
+using System;
+
+public enum BuildingType
+{
+    Shop,
+    AdventurersGuild,
+    Harbor,
+    Inn,
+    House,
+    Other
+}
+
+[System.Serializable]
+public class TownBuilding : MonoBehaviour
+{
+    [Header("Building Configuration")]
+    public string buildingName = "Building";
+    public BuildingType buildingType = BuildingType.Other;
+    public Sprite buildingIcon;
+    public string description = "A building in the town";
+
+    [Header("Visual Settings")]
+    public Vector2Int gridPosition = Vector2Int.zero;
+    public Vector2Int buildingSize = Vector2Int.one;
+    public Color buildingColor = Color.white;
+
+    [Header("Interaction")]
+    public bool isInteractable = true;
+    public string interactionText = "Click to interact";
+
+    protected Action<TownBuilding> onClickCallback;
+    protected VisualElement buildingElement;
+
+    protected virtual void Start()
+    {
+        if (buildingName == "Building")
+            buildingName = gameObject.name;
+    }
+
+    public virtual void SetupClickHandler(Action<TownBuilding> callback)
+    {
+        onClickCallback = callback;
+    }
+
+    public virtual void CreateVisualElement(VisualElement parent)
+    {
+        buildingElement = new VisualElement();
+        buildingElement.name = $"Building_{buildingName}";
+        buildingElement.AddToClassList("town-building");
+
+        // Set position and size based on grid
+        buildingElement.style.position = Position.Absolute;
+        buildingElement.style.left = gridPosition.x * 50; // 50px per grid unit
+        buildingElement.style.top = gridPosition.y * 50;
+        buildingElement.style.width = buildingSize.x * 50;
+        buildingElement.style.height = buildingSize.y * 50;
+        buildingElement.style.backgroundColor = buildingColor;
+
+        // Add click handler
+        if (isInteractable)
+        {
+            buildingElement.RegisterCallback<ClickEvent>(OnBuildingClick);
+            buildingElement.AddToClassList("town-building-interactive");
+        }
+
+        // Add building label
+        var label = new Label(buildingName);
+        label.AddToClassList("building-label");
+        buildingElement.Add(label);
+
+        parent.Add(buildingElement);
+    }
+
+    protected virtual void OnBuildingClick(ClickEvent evt)
+    {
+        if (isInteractable && onClickCallback != null)
+        {
+            onClickCallback.Invoke(this);
+        }
+    }
+
+    public virtual void HighlightBuilding(bool highlight)
+    {
+        if (buildingElement != null)
+        {
+            if (highlight)
+                buildingElement.AddToClassList("town-building-highlighted");
+            else
+                buildingElement.RemoveFromClassList("town-building-highlighted");
+        }
+    }
+}

+ 235 - 5
Assets/Scripts/Town/TownManager.cs

@@ -1,16 +1,246 @@
 using UnityEngine;
+using UnityEngine.UIElements;
+using System.Collections.Generic;
 
 public class TownManager : MonoBehaviour
 {
-    // Start is called once before the first execution of Update after the MonoBehaviour is created
+    [Header("Town Configuration")]
+    public string townName = "Haven Village";
+    public bool hasHarbor = true;
+
+    [Header("UI References")]
+    public UIDocument townUI;
+    public Camera townCamera;
+
+    [Header("Shop Manager")]
+    public TownShopManager shopManager;
+
+    [Header("Team Reference")]
+    [HideInInspector]
+    public TeamCharacter[] currentTeam;
+
+    private VisualElement rootElement;
+
     void Start()
     {
-        
+        InitializeTown();
+        SetupUI();
+        LoadTeamData();
+    }
+
+    private void InitializeTown()
+    {
+        // Check if we have settlement context data
+        if (SettlementContext.Instance != null)
+        {
+            // Use data from settlement context
+            townName = SettlementContext.Instance.settlementName;
+            hasHarbor = SettlementContext.Instance.hasHarbor;
+
+            Debug.Log($"Initialized {townName} ({SettlementContext.Instance.settlementType}) from SettlementContext");
+
+            // Update UI with settlement name
+            UpdateTownNameDisplay();
+        }
+        else
+        {
+            Debug.Log($"Initialized {townName} (no SettlementContext - using defaults)");
+        }
+
+        // Initialize shop manager if not already done
+        if (shopManager == null)
+        {
+            // First check if singleton instance exists
+            if (TownShopManager.Instance != null)
+            {
+                shopManager = TownShopManager.Instance;
+                Debug.Log("TownManager: Using existing TownShopManager singleton");
+            }
+            else
+            {
+                // Try to find any existing instance in scene
+                shopManager = FindFirstObjectByType<TownShopManager>();
+                if (shopManager != null)
+                {
+                    Debug.Log("TownManager: Found existing TownShopManager in scene");
+                }
+            }
+        }
+
+        // If we still don't have a shop manager, create one
+        if (shopManager == null)
+        {
+            Debug.Log("TownManager: Creating new TownShopManager");
+            GameObject shopManagerObj = new GameObject("TownShopManager");
+            shopManager = shopManagerObj.AddComponent<TownShopManager>();
+            shopManager.townUI = townUI;
+        }
+        else
+        {
+            Debug.Log($"TownManager: Using existing TownShopManager: {shopManager.gameObject.name}");
+            // Make sure the existing manager has the correct UI reference
+            if (shopManager.townUI == null)
+            {
+                shopManager.townUI = townUI;
+                Debug.Log("TownManager: Updated TownShopManager UI reference");
+            }
+        }
+    }
+
+    private void SetupUI()
+    {
+        if (townUI == null) return;
+
+        rootElement = townUI.rootVisualElement;
+
+        UpdateTownNameDisplay();
+
+        // Let TownShopManager handle building interactions
+    }
+
+    private void UpdateTownNameDisplay()
+    {
+        if (rootElement == null) return;
+
+        var townNameLabel = rootElement.Q<Label>("TownNameLabel");
+        if (townNameLabel != null)
+            townNameLabel.text = townName;
+    }
+
+    private void LoadTeamData()
+    {
+        // Load team data from GameStateManager or PlayerPrefs
+        var gameStateManager = FindFirstObjectByType<GameStateManager>();
+        if (gameStateManager != null && gameStateManager.savedTeam != null)
+        {
+            currentTeam = gameStateManager.savedTeam;
+            Debug.Log($"Loaded team data: {currentTeam.Length} characters");
+        }
+        else
+        {
+            Debug.LogWarning("No team data found, using test data");
+            CreateTestTeamData();
+        }
+
+        // Update money display
+        UpdateMoneyDisplay();
+    }
+
+    private void CreateTestTeamData()
+    {
+        currentTeam = new TeamCharacter[1];
+        currentTeam[0] = new TeamCharacter("Test Hero", true)
+        {
+            gold = 100,
+            silver = 50,
+            copper = 25
+        };
+    }
+
+    private void UpdateMoneyDisplay()
+    {
+        //if (shopManager != null)
+        //{
+        //    shopManager.UpdateMoneyDisplay();
+        //}
+    }
+
+    private void SaveTeamData()
+    {
+        var gameStateManager = FindFirstObjectByType<GameStateManager>();
+        if (gameStateManager != null)
+        {
+            gameStateManager.savedTeam = currentTeam;
+            // Trigger save to PlayerPrefs if needed
+        }
+    }
+
+    // Called by TownShopManager when a building is clicked
+    public void OnBuildingClicked(TownShop shop)
+    {
+        Debug.Log($"TownManager: Shop clicked: {shop.buildingName} - handled by TownShopManager");
+        // No longer creating duplicate UI here - TownShopManager handles shop opening
+    }
+
+    private void OpenShopDirect(TownShop shop)
+    {
+        // Find existing UI document from the town UI
+        var existingUIDoc = FindFirstObjectByType<UIDocument>();
+
+        // Create shop UI GameObject as a separate top-level object
+        var shopUIObject = new GameObject("TownShopUI");
+
+        // Add UIDocument component and load the UXML
+        var uiDocument = shopUIObject.AddComponent<UIDocument>();
+
+        // Copy settings from existing UI document if available
+        if (existingUIDoc != null)
+        {
+            uiDocument.panelSettings = existingUIDoc.panelSettings;
+            uiDocument.sortingOrder = existingUIDoc.sortingOrder + 100; // Ensure it's on top
+        }
+
+        uiDocument.visualTreeAsset = Resources.Load<VisualTreeAsset>("UI/TownShopUI");
+
+        Debug.Log($"Loaded UXML asset: {uiDocument.visualTreeAsset != null}");
+
+        // If not found in Resources, try direct path
+        if (uiDocument.visualTreeAsset == null)
+        {
+#if UNITY_EDITOR
+            uiDocument.visualTreeAsset = UnityEditor.AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/TownShopUI.uxml");
+            Debug.Log($"Loaded UXML from Assets: {uiDocument.visualTreeAsset != null}");
+#endif
+        }
+
+        if (uiDocument.visualTreeAsset == null)
+        {
+            Debug.LogError("Failed to load TownShopUI UXML!");
+            Destroy(shopUIObject);
+            return;
+        }
+
+        // Add TownShopUI component 
+        var shopUI = shopUIObject.AddComponent<TownShopUI>();
+
+        // CRITICAL: Force the UIDocument to initialize properly
+        uiDocument.enabled = true;
+
+        // Set up the shop UI
+        shopUI.SetShop(shop);
+
+        // Add a small delay to ensure everything is properly set up
+        StartCoroutine(OpenShopAfterFrame(shopUI));
+
+        // Find first available team member as customer
+        if (GameStateManager.Instance?.savedTeam != null)
+        {
+            foreach (var character in GameStateManager.Instance.savedTeam)
+            {
+                if (character != null)
+                {
+                    shopUI.SetCustomer(character);
+                    break;
+                }
+            }
+        }
+
+        // Add a small delay to ensure everything is properly set up
+        StartCoroutine(OpenShopAfterFrame(shopUI));
+
+        Debug.Log($"Opened shop UI for {shop.buildingName} with sortOrder: {uiDocument.sortingOrder}");
+    }
+
+    private System.Collections.IEnumerator OpenShopAfterFrame(TownShopUI townShopUI)
+    {
+        yield return null; // Wait one frame for UI to initialize
+        townShopUI.OpenShop();
+        Debug.Log("Shop opened after frame delay");
     }
 
-    // Update is called once per frame
-    void Update()
+    public void ReturnToMap()
     {
-        
+        SaveTeamData();
+        UnityEngine.SceneManagement.SceneManager.LoadScene("MapScene2");
     }
 }

+ 275 - 0
Assets/Scripts/Town/TownSetupHelper.cs

@@ -0,0 +1,275 @@
+using UnityEngine;
+using UnityEngine.UIElements;
+using System.Collections.Generic;
+
+[System.Serializable]
+public class TownSetupHelper : MonoBehaviour
+{
+    [Header("Auto-Setup Configuration")]
+    public bool createSampleShops = true;
+    public bool loadSampleItems = true;
+
+    [Header("Generated Shops")]
+    public TownShop weaponShop;
+    public TownShop armorShop;
+    public TownShop potionShop;
+    public TownShop generalStore;
+
+    [ContextMenu("Setup Sample Town")]
+    public void SetupSampleTown()
+    {
+        if (createSampleShops)
+        {
+            CreateShopGameObjects();
+        }
+
+        if (loadSampleItems)
+        {
+            LoadSampleItemsToShops();
+        }
+
+        Debug.Log("Sample town setup complete!");
+    }
+
+    private void CreateShopGameObjects()
+    {
+        // Create Weapon Shop
+        if (weaponShop == null)
+        {
+            var weaponShopGO = new GameObject("WeaponShop");
+            weaponShopGO.transform.SetParent(transform);
+            weaponShop = weaponShopGO.AddComponent<TownShop>();
+            ConfigureWeaponShop();
+        }
+
+        // Create Armor Shop
+        if (armorShop == null)
+        {
+            var armorShopGO = new GameObject("ArmorShop");
+            armorShopGO.transform.SetParent(transform);
+            armorShop = armorShopGO.AddComponent<TownShop>();
+            ConfigureArmorShop();
+        }
+
+        // Create Potion Shop
+        if (potionShop == null)
+        {
+            var potionShopGO = new GameObject("PotionShop");
+            potionShopGO.transform.SetParent(transform);
+            potionShop = potionShopGO.AddComponent<TownShop>();
+            ConfigurePotionShop();
+        }
+
+        // Create General Store
+        if (generalStore == null)
+        {
+            var generalStoreGO = new GameObject("GeneralStore");
+            generalStoreGO.transform.SetParent(transform);
+            generalStore = generalStoreGO.AddComponent<TownShop>();
+            ConfigureGeneralStore();
+        }
+    }
+
+    private void ConfigureWeaponShop()
+    {
+        weaponShop.buildingName = "The Forge";
+        weaponShop.shopType = ShopType.Weapons;
+        weaponShop.shopkeeperName = "Gareth the Smith";
+        weaponShop.profitMargin = 1.3f; // 30% markup
+        weaponShop.sellbackRate = 0.6f; // 60% when selling back
+        weaponShop.description = "Fine weapons crafted by the town's master smith";
+        weaponShop.isInteractable = true;
+        weaponShop.buildingColor = new Color(0.8f, 0.2f, 0.2f); // Red
+    }
+
+    private void ConfigureArmorShop()
+    {
+        armorShop.buildingName = "Ironclad Armory";
+        armorShop.shopType = ShopType.Armor;
+        armorShop.shopkeeperName = "Miranda the Armorer";
+        armorShop.profitMargin = 1.25f; // 25% markup
+        armorShop.sellbackRate = 0.6f;
+        armorShop.description = "Protective gear for the discerning adventurer";
+        armorShop.isInteractable = true;
+        armorShop.buildingColor = new Color(0.2f, 0.2f, 0.8f); // Blue
+    }
+
+    private void ConfigurePotionShop()
+    {
+        potionShop.buildingName = "The Bubbling Cauldron";
+        potionShop.shopType = ShopType.Potions;
+        potionShop.shopkeeperName = "Elias the Alchemist";
+        potionShop.profitMargin = 1.4f; // 40% markup (potions are specialized)
+        potionShop.sellbackRate = 0.5f; // Lower sellback for consumables
+        potionShop.description = "Magical elixirs and healing draughts";
+        potionShop.isInteractable = true;
+        potionShop.buildingColor = new Color(0.2f, 0.8f, 0.2f); // Green
+    }
+
+    private void ConfigureGeneralStore()
+    {
+        generalStore.buildingName = "Pete's General Goods";
+        generalStore.shopType = ShopType.General;
+        generalStore.shopkeeperName = "Old Pete";
+        generalStore.profitMargin = 1.2f; // 20% markup
+        generalStore.sellbackRate = 0.65f; // Better sellback for general goods
+        generalStore.description = "Everything an adventurer needs, and some things they don't";
+        generalStore.isInteractable = true;
+        generalStore.buildingColor = new Color(1f, 0.65f, 0f); // Orange
+    }
+
+    private void LoadSampleItemsToShops()
+    {
+        // Load all items from Resources
+        var allWeapons = Resources.LoadAll<WeaponItem>("Items/Weapons");
+        var allArmor = Resources.LoadAll<ArmorItem>("Items/Armor");
+        var allMisc = Resources.LoadAll<MiscellaneousItem>("Items/Miscellaneous");
+
+        Debug.Log($"Loaded {allWeapons.Length} weapons, {allArmor.Length} armor pieces, {allMisc.Length} misc items");
+
+        // Add weapons to weapon shop
+        if (weaponShop != null)
+        {
+            weaponShop.baseInventory.Clear();
+            foreach (var weapon in allWeapons)
+            {
+                if (weapon != null)
+                    weaponShop.baseInventory.Add(weapon);
+            }
+            Debug.Log($"Added {allWeapons.Length} weapons to weapon shop");
+        }
+
+        // Add armor to armor shop
+        if (armorShop != null)
+        {
+            armorShop.baseInventory.Clear();
+            foreach (var armor in allArmor)
+            {
+                if (armor != null)
+                    armorShop.baseInventory.Add(armor);
+            }
+            Debug.Log($"Added {allArmor.Length} armor pieces to armor shop");
+        }
+
+        // Add consumables to potion shop
+        if (potionShop != null)
+        {
+            potionShop.baseInventory.Clear();
+            foreach (var misc in allMisc)
+            {
+                if (misc != null && misc.itemType == ItemType.Consumable)
+                    potionShop.baseInventory.Add(misc);
+            }
+            Debug.Log($"Added consumables to potion shop");
+        }
+
+        // Add everything to general store (smaller selection)
+        if (generalStore != null)
+        {
+            generalStore.baseInventory.Clear();
+
+            // Add a few basic weapons
+            for (int i = 0; i < Mathf.Min(3, allWeapons.Length); i++)
+            {
+                if (allWeapons[i] != null)
+                    generalStore.baseInventory.Add(allWeapons[i]);
+            }
+
+            // Add a few basic armor pieces
+            for (int i = 0; i < Mathf.Min(3, allArmor.Length); i++)
+            {
+                if (allArmor[i] != null)
+                    generalStore.baseInventory.Add(allArmor[i]);
+            }
+
+            // Add misc items
+            foreach (var misc in allMisc)
+            {
+                if (misc != null && misc.itemType != ItemType.Consumable)
+                    generalStore.baseInventory.Add(misc);
+            }
+
+            Debug.Log($"Added mixed items to general store");
+        }
+    }
+
+    [ContextMenu("Create Test Items")]
+    public void CreateTestItems()
+    {
+        CreateTestWeapons();
+        CreateTestArmor();
+        CreateTestConsumables();
+        CreateTestMiscItems();
+    }
+
+    private void CreateTestWeapons()
+    {
+        // This would create ScriptableObject assets - but that requires editor scripts
+        // For now, just log what would be created
+        Debug.Log("Test weapons that should be created:");
+        Debug.Log("- Simple Sword (15g) - Basic iron blade");
+        Debug.Log("- War Axe (22g) - Heavy two-handed axe");
+        Debug.Log("- Hunting Bow (18g) - Reliable ranged weapon");
+        Debug.Log("- Iron Dagger (8g) - Quick and light");
+        Debug.Log("- Wooden Staff (12g) - For spellcasters");
+    }
+
+    private void CreateTestArmor()
+    {
+        Debug.Log("Test armor that should be created:");
+        Debug.Log("- Leather Vest (10g) - Light chest protection");
+        Debug.Log("- Iron Helmet (15g) - Sturdy head protection");
+        Debug.Log("- Chainmail Shirt (35g) - Medium protection");
+        Debug.Log("- Leather Boots (6g) - Basic foot protection");
+        Debug.Log("- Iron Gauntlets (12g) - Hand protection");
+    }
+
+    private void CreateTestConsumables()
+    {
+        Debug.Log("Test consumables that should be created:");
+        Debug.Log("- Health Potion (5g) - Restores 25 HP");
+        Debug.Log("- Mana Potion (7g) - Restores 15 MP");
+        Debug.Log("- Antidote (3g) - Cures poison");
+        Debug.Log("- Stamina Elixir (4g) - Restores energy");
+    }
+
+    private void CreateTestMiscItems()
+    {
+        Debug.Log("Test misc items that should be created:");
+        Debug.Log("- Hemp Rope (2g) - 50 feet of rope");
+        Debug.Log("- Torch (1g) - Provides light");
+        Debug.Log("- Lockpicks (8g) - For opening locks");
+        Debug.Log("- Camping Kit (15g) - For resting outdoors");
+        Debug.Log("- Waterskin (3g) - Holds water");
+    }
+
+    [ContextMenu("Setup Shop Manager")]
+    public void SetupShopManager()
+    {
+        var shopManager = FindFirstObjectByType<TownShopManager>();
+        if (shopManager == null)
+        {
+            var shopManagerGO = new GameObject("ShopManager");
+            shopManagerGO.transform.SetParent(transform);
+            shopManager = shopManagerGO.AddComponent<TownShopManager>();
+        }
+
+        // Create the shops array
+        var shops = new List<TownShop>();
+        if (weaponShop != null) shops.Add(weaponShop);
+        if (armorShop != null) shops.Add(armorShop);
+        if (potionShop != null) shops.Add(potionShop);
+        if (generalStore != null) shops.Add(generalStore);
+
+        shopManager.allShops = shops.ToArray();
+
+        // Try to link UI
+        var uiDocument = FindFirstObjectByType<UIDocument>();
+        if (uiDocument != null)
+        {
+            shopManager.townUI = uiDocument;
+        }
+
+        Debug.Log($"Setup shop manager with {shops.Count} shops");
+    }
+}

+ 271 - 0
Assets/Scripts/Town/TownShop.cs

@@ -0,0 +1,271 @@
+using UnityEngine;
+using System.Collections.Generic;
+using System.Linq;
+
+public enum ShopType
+{
+    Weapons,
+    Armor,
+    Potions,
+    General,
+    Magic,
+    Tools
+}
+
+[System.Serializable]
+public class TownShop : TownBuilding
+{
+    [Header("Shop Configuration")]
+    public ShopType shopType = ShopType.General;
+    public string shopkeeperName = "Merchant";
+    public float profitMargin = 1.2f; // 20% markup on base item prices
+    public float sellbackRate = 0.6f; // Player gets 60% of base price when selling
+
+    [Header("Shop Inventory")]
+    public List<Item> baseInventory = new List<Item>();
+    public int maxInventorySize = 20;
+    public bool restockDaily = true;
+
+    [Header("Shop Filters")]
+    public List<ItemType> acceptedItemTypes = new List<ItemType>();
+    public List<ItemRarity> acceptedRarities = new List<ItemRarity>();
+
+    public List<ShopInventoryItem> currentInventory = new List<ShopInventoryItem>();
+    private System.DateTime lastRestockTime;
+
+    protected override void Start()
+    {
+        base.Start();
+        buildingType = BuildingType.Shop;
+        InitializeShop();
+    }
+    private void InitializeShop()
+    {
+        // Set default accepted item types based on shop type
+        if (acceptedItemTypes.Count == 0)
+        {
+            switch (shopType)
+            {
+                case ShopType.Weapons:
+                    acceptedItemTypes.Add(ItemType.Weapon);
+                    break;
+                case ShopType.Armor:
+                    acceptedItemTypes.Add(ItemType.Armor);
+                    acceptedItemTypes.Add(ItemType.Accessory);
+                    break;
+                case ShopType.Potions:
+                    acceptedItemTypes.Add(ItemType.Consumable);
+                    break;
+                case ShopType.General:
+                    acceptedItemTypes.AddRange(System.Enum.GetValues(typeof(ItemType)).Cast<ItemType>());
+                    break;
+                case ShopType.Tools:
+                    acceptedItemTypes.Add(ItemType.Tool);
+                    acceptedItemTypes.Add(ItemType.Miscellaneous);
+                    break;
+            }
+        }
+
+        // Initialize inventory
+        RestockInventory();
+
+        // Set building colors based on shop type
+        switch (shopType)
+        {
+            case ShopType.Weapons:
+                buildingColor = new Color(0.8f, 0.2f, 0.2f); // Red
+                break;
+            case ShopType.Armor:
+                buildingColor = new Color(0.2f, 0.2f, 0.8f); // Blue
+                break;
+            case ShopType.Potions:
+                buildingColor = new Color(0.2f, 0.8f, 0.2f); // Green
+                break;
+            case ShopType.General:
+                buildingColor = new Color(0.6f, 0.4f, 0.2f); // Brown
+                break;
+            default:
+                buildingColor = Color.gray;
+                break;
+        }
+    }
+
+    public void RestockInventory()
+    {
+        currentInventory.Clear();
+
+        // Add base inventory items with markup
+        foreach (var item in baseInventory)
+        {
+            if (item != null)
+            {
+                var shopItem = new ShopInventoryItem(item, profitMargin);
+                currentInventory.Add(shopItem);
+            }
+        }
+
+        // Add some random items based on shop type
+        AddRandomItems();
+
+        lastRestockTime = System.DateTime.Now;
+        Debug.Log($"{buildingName} restocked with {currentInventory.Count} items");
+    }
+
+    private void AddRandomItems()
+    {
+        // Get all items of appropriate types from Resources
+        var allItems = Resources.LoadAll<Item>("Items");
+        var filteredItems = allItems.Where(item =>
+            acceptedItemTypes.Contains(item.itemType) &&
+            (acceptedRarities.Count == 0 || acceptedRarities.Contains(item.rarity))
+        ).ToList();
+
+        // Add 3-5 random items
+        int randomItemCount = Random.Range(3, 6);
+        for (int i = 0; i < randomItemCount && currentInventory.Count < maxInventorySize; i++)
+        {
+            if (filteredItems.Count > 0)
+            {
+                var randomItem = filteredItems[Random.Range(0, filteredItems.Count)];
+                var shopItem = new ShopInventoryItem(randomItem, profitMargin);
+                currentInventory.Add(shopItem);
+            }
+        }
+    }
+
+    public List<ShopInventoryItem> GetInventory()
+    {
+        // Check if restock is needed
+        if (restockDaily && (System.DateTime.Now - lastRestockTime).TotalDays >= 1)
+        {
+            RestockInventory();
+        }
+
+        return new List<ShopInventoryItem>(currentInventory);
+    }
+
+    public bool CanBuyItem(Item item)
+    {
+        return acceptedItemTypes.Contains(item.itemType) &&
+               (acceptedRarities.Count == 0 || acceptedRarities.Contains(item.rarity));
+    }
+
+    public int GetSellPrice(Item item)
+    {
+        if (!CanBuyItem(item)) return 0;
+
+        int basePrice = item.goldCost * 100 + item.silverCost * 10 + item.copperCost;
+        return Mathf.RoundToInt(basePrice * sellbackRate);
+    }
+
+    public void SellItemToShop(Item item, TeamCharacter seller)
+    {
+        if (!CanBuyItem(item)) return;
+
+        int sellPrice = GetSellPrice(item);
+
+        // Convert copper to gold/silver/copper
+        int gold = sellPrice / 100;
+        sellPrice %= 100;
+        int silver = sellPrice / 10;
+        int copper = sellPrice % 10;
+
+        // Add money to seller
+        seller.gold += gold;
+        seller.silver += silver;
+        seller.copper += copper;
+
+        // Normalize currency (convert excess copper/silver)
+        if (seller.copper >= 10)
+        {
+            seller.silver += seller.copper / 10;
+            seller.copper %= 10;
+        }
+        if (seller.silver >= 10)
+        {
+            seller.gold += seller.silver / 10;
+            seller.silver %= 10;
+        }
+
+        Debug.Log($"Sold {item.itemName} to {buildingName} for {gold}g {silver}s {copper}c");
+    }
+
+    /// <summary>
+    /// Update shop names after initialization (called by TownShopManager)
+    /// </summary>
+    public void UpdateNames(string newBuildingName, string newShopkeeperName)
+    {
+        this.buildingName = newBuildingName;
+        this.shopkeeperName = newShopkeeperName;
+        Debug.Log($"TownShop: Updated names to '{this.buildingName}' run by '{this.shopkeeperName}'");
+    }
+}
+
+[System.Serializable]
+public class ShopInventoryItem
+{
+    public Item item;
+    public int markupGold;
+    public int markupSilver;
+    public int markupCopper;
+    public int quantity;
+    public bool isUnlimited;
+
+    public ShopInventoryItem(Item baseItem, float profitMargin, int qty = 1, bool unlimited = false)
+    {
+        item = baseItem;
+        quantity = qty;
+        isUnlimited = unlimited;
+
+        // Calculate markup prices
+        int baseCopperPrice = baseItem.goldCost * 100 + baseItem.silverCost * 10 + baseItem.copperCost;
+        int markupCopperPrice = Mathf.RoundToInt(baseCopperPrice * profitMargin);
+
+        markupGold = markupCopperPrice / 100;
+        markupCopperPrice %= 100;
+        markupSilver = markupCopperPrice / 10;
+        markupCopper = markupCopperPrice % 10;
+    }
+
+    public bool CanAfford(TeamCharacter customer)
+    {
+        if (customer == null || quantity <= 0) return false;
+
+        int totalCopperCost = markupGold * 100 + markupSilver * 10 + markupCopper;
+        int totalCopperAvailable = customer.gold * 100 + customer.silver * 10 + customer.copper;
+        return totalCopperAvailable >= totalCopperCost;
+    }
+
+    public void Purchase(TeamCharacter customer)
+    {
+        if (!CanAfford(customer) || quantity <= 0) return;
+
+        // Deduct money
+        int totalCopperCost = markupGold * 100 + markupSilver * 10 + markupCopper;
+        int totalCopperAvailable = customer.gold * 100 + customer.silver * 10 + customer.copper;
+        int remainingCopper = totalCopperAvailable - totalCopperCost;
+
+        customer.gold = remainingCopper / 100;
+        remainingCopper %= 100;
+        customer.silver = remainingCopper / 10;
+        customer.copper = remainingCopper % 10;
+
+        // Add item to customer inventory
+        // This will be handled by the shop UI
+
+        // Reduce quantity
+        if (!isUnlimited)
+            quantity--;
+
+        Debug.Log($"Purchased {item.itemName} for {markupGold}g {markupSilver}s {markupCopper}c");
+    }
+
+    public string GetPriceString()
+    {
+        string price = "";
+        if (markupGold > 0) price += $"{markupGold}g ";
+        if (markupSilver > 0) price += $"{markupSilver}s ";
+        if (markupCopper > 0) price += $"{markupCopper}c";
+        return price.Trim();
+    }
+}

+ 1045 - 0
Assets/Scripts/Town/TownShopManager.cs

@@ -0,0 +1,1045 @@
+using UnityEngine;
+using UnityEngine.UIElements;
+using System.Collections.Generic;
+using System.Collections;
+using System.Linq;
+
+public class TownShopManager : MonoBehaviour
+{
+    [Header("Shop Configuration")]
+    public TownShop[] allShops;
+
+    [Header("UI References")]
+    public UIDocument townUI;
+
+    private Dictionary<string, TownShop> shopLookup = new Dictionary<string, TownShop>();
+    private Dictionary<string, EventCallback<ClickEvent>> clickCallbacks = new Dictionary<string, EventCallback<ClickEvent>>();
+    private VisualElement rootElement;
+
+    // Singleton pattern to prevent multiple instances
+    private static TownShopManager instance;
+    public static TownShopManager Instance => instance;
+
+    // Prevent multiple shop UI creation
+    private bool isShopUIOpen = false;
+
+    void Awake()
+    {
+        Debug.Log($"TownShopManager.Awake() called on {gameObject.name}");
+
+        // Check if another instance already exists
+        if (instance != null)
+        {
+            if (instance == this)
+            {
+                Debug.Log($"TownShopManager: Same instance re-awakening on {gameObject.name}");
+            }
+            else
+            {
+                Debug.LogWarning($"Duplicate TownShopManager detected! Existing: {instance.gameObject.name}, New: {gameObject.name}");
+
+                // Before destroying, transfer any UI reference to the existing instance
+                if (townUI != null && instance.townUI == null)
+                {
+                    Debug.Log("Transferring UI reference to existing singleton");
+                    instance.townUI = townUI;
+
+                    // Also transfer rootElement if available
+                    if (instance.rootElement == null && townUI != null)
+                    {
+                        instance.rootElement = townUI.rootVisualElement;
+                    }
+                }
+
+                Debug.LogWarning($"Destroying duplicate on {gameObject.name}");
+                Destroy(gameObject);
+                return;
+            }
+        }
+        else
+        {
+            instance = this;
+            Debug.Log($"TownShopManager singleton established on {gameObject.name}");
+        }
+
+        // Configure shops immediately in Awake to ensure they're ready before Start()
+        StartCoroutine(ConfigureShopsEarly());
+    }
+
+    private System.Collections.IEnumerator ConfigureShopsEarly()
+    {
+        Debug.Log($"ConfigureShopsEarly starting on {gameObject.name}");
+
+        // Wait a few frames for SettlementContext to be available and TownShop components to start
+        yield return null;
+        yield return null;
+        yield return null;
+
+        Debug.Log($"TownShopManager: Configuring shops early in Awake on {gameObject.name}");
+
+        // Always create default shops first (creates the GameObjects)
+        if (allShops == null || allShops.Length == 0)
+        {
+            Debug.Log($"Creating default shops on {gameObject.name}");
+            CreateDefaultShops();
+            Debug.Log($"After CreateDefaultShops: allShops.Length = {allShops?.Length ?? 0}");
+        }
+        else
+        {
+            Debug.Log($"Shops already exist: {allShops.Length} shops");
+        }
+
+        // Wait another frame for shops to finish their Start() methods
+        yield return null;
+
+        // Then configure them based on SettlementContext if available
+        if (SettlementContext.Instance != null)
+        {
+            Debug.Log($"=== SETTLEMENT DEBUG on {gameObject.name} ===");
+            Debug.Log($"Settlement Name: {SettlementContext.Instance.settlementName}");
+            Debug.Log($"Settlement Type: {SettlementContext.Instance.settlementType}");
+            Debug.Log($"Settlement Seed: {SettlementContext.Instance.settlementSeed}");
+            Debug.Log($"=== Configuring shops for {SettlementContext.Instance.settlementType} ===");
+            ConfigureShopsFromSettlement();
+            UpdateAllBuildingNames();
+        }
+        else
+        {
+            Debug.LogWarning("TownShopManager: SettlementContext.Instance is NULL in Awake - shops will use default names");
+            // Configure with default names when no SettlementContext (for testing)
+            ConfigureShopsWithDefaults();
+        }
+
+        // Build the shop lookup table BEFORE setting up UI
+        Debug.Log($"ConfigureShopsEarly: Building shop lookup table for {allShops?.Length ?? 0} shops");
+        shopLookup.Clear();
+        if (allShops != null)
+        {
+            foreach (var shop in allShops)
+            {
+                if (shop != null)
+                {
+                    string elementName = GetUIElementNameForShop(shop);
+                    shopLookup[elementName] = shop;
+                    Debug.Log($"Added to lookup: {shop.buildingName} -> {elementName}");
+                }
+            }
+        }
+
+        // NOW setup UI after shops are properly configured AND lookup is built
+        Debug.Log($"ConfigureShopsEarly: Setting up UI with {allShops?.Length ?? 0} shops, lookup: {shopLookup.Count}");
+        if (rootElement != null && allShops != null && allShops.Length > 0 && shopLookup.Count > 0)
+        {
+            SetupUIClickHandlers();
+            UpdateMoneyDisplay();
+            UpdateBuildingVisibility();
+            UpdateAllBuildingNames();
+            Debug.Log("ConfigureShopsEarly: UI setup completed");
+        }
+        else
+        {
+            Debug.LogWarning($"ConfigureShopsEarly: Cannot setup UI - rootElement: {rootElement != null}, allShops: {allShops?.Length ?? 0}, lookup: {shopLookup.Count}");
+        }
+    }
+
+    private void ConfigureShopsWithDefaults()
+    {
+        Debug.Log("TownShopManager: Using default shop configuration");
+
+        if (allShops == null) return;
+
+        foreach (var shop in allShops)
+        {
+            if (shop != null)
+            {
+                // Use shop type as default name if not already set properly
+                string defaultName = $"{shop.shopType} Shop";
+                string defaultKeeper = "Merchant";
+
+                shop.UpdateNames(defaultName, defaultKeeper);
+                Debug.Log($"Set default name: {shop.buildingName}");
+            }
+        }
+    }
+
+    void OnDestroy()
+    {
+        // Clear singleton reference when destroyed
+        if (instance == this)
+        {
+            instance = null;
+            Debug.Log("TownShopManager singleton cleared");
+        }
+    }
+
+    void Start()
+    {
+        Debug.Log($"TownShopManager.Start() called on {gameObject.name}, instance == this: {instance == this}");
+        Debug.Log($"Current singleton instance: {(instance != null ? instance.gameObject.name : "NULL")}");
+
+        // Only start if this is the active instance
+        if (instance == this)
+        {
+            Debug.Log($"TownShopManager.Start() - Active instance on {gameObject.name}");
+            Debug.Log($"allShops status: {(allShops != null ? $"Array with {allShops.Length} items" : "NULL")}");
+
+            // Check if townUI is assigned
+            if (townUI == null)
+            {
+                Debug.LogError("TownShopManager: townUI is not assigned in the inspector!");
+                return;
+            }
+
+            // Get root element from townUI
+            rootElement = townUI.rootVisualElement;
+            if (rootElement == null)
+            {
+                Debug.LogError("TownShopManager: Could not get rootVisualElement from townUI!");
+                return;
+            }
+
+            Debug.Log($"TownShopManager: UI initialized - townUI: {townUI != null}, rootElement: {rootElement != null}");
+
+            // NOTE: Shop configuration and UI setup will happen in ConfigureShopsEarly coroutine
+            // Don't setup UI here since shops might not be ready yet
+            Debug.Log("TownShopManager: Waiting for ConfigureShopsEarly to complete before setting up UI");
+        }
+        else
+        {
+            Debug.LogWarning($"TownShopManager.Start() - Inactive instance on {gameObject.name}, skipping initialization");
+        }
+    }
+
+    /// <summary>
+    /// Public method to reinitialize shops and UI (for testing)
+    /// </summary>
+    public void ReinitializeShopsAndUI()
+    {
+        Debug.Log("Reinitializing shops and UI...");
+
+        // Clear existing UI event handlers to prevent duplicates
+        ClearUIClickHandlers();
+
+        // Reinitialize shops
+        InitializeShops();
+
+        // Setup UI again
+        SetupUIClickHandlers();
+        UpdateMoneyDisplay();
+    }
+
+    /// <summary>
+    /// Clear all UI click handlers to prevent duplicates
+    /// </summary>
+    private void ClearUIClickHandlers()
+    {
+        if (rootElement == null) return;
+
+        // Clear stored callbacks first
+        foreach (var kvp in clickCallbacks)
+        {
+            var element = rootElement.Q<VisualElement>(kvp.Key);
+            if (element != null)
+            {
+                element.UnregisterCallback<ClickEvent>(kvp.Value);
+                Debug.Log($"Cleared stored callback for {kvp.Key}");
+            }
+        }
+        clickCallbacks.Clear();
+
+        // Also clear any OnAnyShopClicked callbacks as fallback
+        var shopElements = new string[] { "WeaponShop", "ArmorShop", "PotionShop", "GeneralStore" };
+        foreach (var elementName in shopElements)
+        {
+            var element = rootElement.Q<VisualElement>(elementName);
+            if (element != null)
+            {
+                element.UnregisterCallback<ClickEvent>(OnAnyShopClicked);
+                Debug.Log($"Cleared fallback callbacks for {elementName}");
+            }
+        }
+    }
+
+    public void InitializeShops()
+    {
+        shopLookup.Clear();
+
+        // Ensure shops exist before trying to initialize them
+        if (allShops == null || allShops.Length == 0)
+        {
+            Debug.LogWarning("TownShopManager.InitializeShops() - allShops is null or empty, creating default shops");
+            CreateDefaultShops();
+        }
+
+        if (allShops == null)
+        {
+            Debug.LogError("TownShopManager.InitializeShops() - Failed to create shops, cannot continue");
+            return;
+        }
+
+        // Shops should already be configured by ConfigureShopsEarly() in Awake
+        Debug.Log($"TownShopManager.InitializeShops() - Building shop lookup table for {allShops.Length} shops");
+
+        foreach (var shop in allShops)
+        {
+            if (shop != null)
+            {
+                // Map shop to UI element by name
+                string elementName = GetUIElementNameForShop(shop);
+                shopLookup[elementName] = shop;
+
+                Debug.Log($"Registered shop: {shop.buildingName} -> {elementName}");
+            }
+        }
+    }
+
+    private void CreateDefaultShops()
+    {
+        Debug.Log($"Creating default shops on {gameObject.name}...");
+        var setupHelper = GetComponent<TownSetupHelper>();
+        if (setupHelper == null)
+        {
+            setupHelper = gameObject.AddComponent<TownSetupHelper>();
+            Debug.Log($"Added TownSetupHelper to {gameObject.name}");
+        }
+
+        setupHelper.SetupSampleTown();
+
+        // Collect the created shops
+        List<TownShop> shopList = new List<TownShop>();
+        if (setupHelper.weaponShop != null) shopList.Add(setupHelper.weaponShop);
+        if (setupHelper.armorShop != null) shopList.Add(setupHelper.armorShop);
+        if (setupHelper.potionShop != null) shopList.Add(setupHelper.potionShop);
+        if (setupHelper.generalStore != null) shopList.Add(setupHelper.generalStore);
+
+        allShops = shopList.ToArray();
+        Debug.Log($"CreateDefaultShops completed on {gameObject.name}: {allShops.Length} shops created");
+        foreach (var shop in allShops)
+        {
+            Debug.Log($"  - {shop.buildingName} ({shop.shopType}) on {shop.gameObject.name}");
+        }
+    }
+
+    private void ConfigureShopsFromSettlement()
+    {
+        if (SettlementContext.Instance == null || allShops == null)
+        {
+            Debug.LogError("ConfigureShopsFromSettlement: Missing SettlementContext or allShops!");
+            return;
+        }
+
+        var settlementType = SettlementContext.Instance.settlementType;
+        var settlementName = SettlementContext.Instance.settlementName;
+        var mapPosition = SettlementContext.Instance.mapPosition;
+
+        Debug.Log($"=== CONFIGURE SHOPS DEBUG ===");
+        Debug.Log($"Settlement: {settlementName} ({settlementType})");
+        Debug.Log($"Total shops to configure: {allShops.Length}");
+
+        // First, randomize all shop names based on settlement
+        foreach (var shop in allShops)
+        {
+            if (shop != null)
+            {
+                string newBuildingName = ShopNameGenerator.GenerateUniqueShopName(shop.shopType, settlementName, mapPosition);
+                string newShopkeeperName = ShopNameGenerator.GenerateUniqueShopkeeperName(shop.shopType, settlementName, mapPosition);
+
+                // Update names using the shop's UpdateNames method
+                shop.UpdateNames(newBuildingName, newShopkeeperName);
+
+                Debug.Log($"Configured shop: {shop.buildingName} run by {shop.shopkeeperName} (GameObject: {shop.gameObject.name}, Active: {shop.gameObject.activeInHierarchy})");
+            }
+        }
+
+        // For villages, disable some shops
+        if (settlementType == SettlementType.Village)
+        {
+            Debug.Log($"=== VILLAGE CONFIGURATION START ===");
+            Debug.Log($"Configuring for village: {settlementName}");
+            Debug.Log($"Total shops before: {allShops?.Length ?? 0}");
+
+            // Count shops that are actually active before we start
+            int activeShopsBefore = 0;
+            foreach (var shop in allShops)
+            {
+                if (shop != null && shop.gameObject.activeInHierarchy)
+                {
+                    activeShopsBefore++;
+                }
+            }
+            Debug.Log($"Active shops before village config: {activeShopsBefore}");
+
+            // First, disable all shops
+            foreach (var shop in allShops)
+            {
+                if (shop != null)
+                {
+                    bool wasPreviouslyActive = shop.gameObject.activeInHierarchy;
+                    shop.gameObject.SetActive(false);
+                    Debug.Log($"Village: Disabled {shop.buildingName} ({shop.shopType}) - Was active: {wasPreviouslyActive}, Now active: {shop.gameObject.activeInHierarchy}");
+                }
+            }
+
+            // Count shops that are actually disabled after we disable them
+            int activeShopsAfterDisable = 0;
+            foreach (var shop in allShops)
+            {
+                if (shop != null && shop.gameObject.activeInHierarchy)
+                {
+                    activeShopsAfterDisable++;
+                }
+            }
+            Debug.Log($"Active shops after disabling all: {activeShopsAfterDisable}");
+
+            var random = new System.Random(SettlementContext.Instance.settlementSeed);
+            Debug.Log($"Using village seed: {SettlementContext.Instance.settlementSeed}");
+
+            // Always keep general store
+            var generalStore = allShops.FirstOrDefault(s => s != null && s.shopType == ShopType.General);
+            if (generalStore != null)
+            {
+                bool wasActive = generalStore.gameObject.activeInHierarchy;
+                generalStore.gameObject.SetActive(true);
+                Debug.Log($"Village: Enabled General Store - Was active: {wasActive}, Now active: {generalStore.gameObject.activeInHierarchy}, Building: {generalStore.buildingName}");
+            }
+            else
+            {
+                Debug.LogError("Village: No General Store found!");
+            }
+
+            // Maybe keep one other shop (60% chance)
+            double randomValue = random.NextDouble();
+            Debug.Log($"Village: Random value for second shop: {randomValue} (>0.4 = keep second shop)");
+
+            if (randomValue > 0.4)
+            {
+                var eligibleShops = allShops.Where(s => s != null && s.shopType != ShopType.General).ToArray();
+                Debug.Log($"Village: Found {eligibleShops.Length} eligible shops for second shop");
+
+                if (eligibleShops.Length > 0)
+                {
+                    var selectedShop = eligibleShops[random.Next(eligibleShops.Length)];
+                    bool wasActive = selectedShop.gameObject.activeInHierarchy;
+                    selectedShop.gameObject.SetActive(true);
+                    Debug.Log($"Village: Also enabled {selectedShop.buildingName} ({selectedShop.shopType}) - Was active: {wasActive}, Now active: {selectedShop.gameObject.activeInHierarchy}");
+                }
+            }
+            else
+            {
+                Debug.Log("Village: Only keeping General Store (random value <= 0.4)");
+            }
+
+            // Final count of active shops
+            int finalActiveShops = 0;
+            foreach (var shop in allShops)
+            {
+                if (shop != null && shop.gameObject.activeInHierarchy)
+                {
+                    finalActiveShops++;
+                    Debug.Log($"Village Final: {shop.buildingName} ({shop.shopType}) is ACTIVE");
+                }
+                else if (shop != null)
+                {
+                    Debug.Log($"Village Final: {shop.buildingName} ({shop.shopType}) is DISABLED");
+                }
+            }
+            Debug.Log($"=== VILLAGE CONFIGURATION END - Final active shops: {finalActiveShops} ===");
+        }
+        else // Town
+        {
+            Debug.Log("Configuring for town - enabling all shops");
+            // Towns have all shops available
+            foreach (var shop in allShops)
+            {
+                if (shop != null)
+                {
+                    shop.gameObject.SetActive(true);
+                    Debug.Log($"Town: Enabling {shop.buildingName}");
+                }
+            }
+        }
+
+        UpdateAllBuildingNames();
+    }
+
+    private void UpdateBuildingVisibility()
+    {
+        if (rootElement == null)
+        {
+            Debug.LogWarning("UpdateBuildingVisibility: rootElement is null!");
+            return;
+        }
+
+        Debug.Log("=== UPDATE BUILDING VISIBILITY START ===");
+
+        // Check if allShops is null or empty
+        if (allShops == null || allShops.Length == 0)
+        {
+            Debug.LogWarning("UpdateBuildingVisibility: allShops is null or empty!");
+            return;
+        }
+
+        // Get all shop types that are available and active
+        var availableShopTypes = new System.Collections.Generic.HashSet<ShopType>();
+        foreach (var shop in allShops)
+        {
+            if (shop != null && shop.gameObject.activeInHierarchy)
+            {
+                availableShopTypes.Add(shop.shopType);
+                Debug.Log($"Available shop type: {shop.shopType} ({shop.buildingName})");
+            }
+            else if (shop != null)
+            {
+                Debug.Log($"Unavailable shop type: {shop.shopType} ({shop.buildingName}) - GameObject active: {shop.gameObject.activeInHierarchy}");
+            }
+        }
+
+        Debug.Log($"Total available shop types: {availableShopTypes.Count}");
+
+        // Show/hide buildings based on what's available
+        var allShopElements = new string[] { "WeaponShop", "ArmorShop", "PotionShop", "GeneralStore" };
+        var correspondingTypes = new ShopType[] { ShopType.Weapons, ShopType.Armor, ShopType.Potions, ShopType.General };
+
+        for (int i = 0; i < allShopElements.Length; i++)
+        {
+            var element = rootElement.Q<VisualElement>(allShopElements[i]);
+            if (element != null)
+            {
+                bool shouldShow = availableShopTypes.Contains(correspondingTypes[i]);
+                var previousDisplay = element.style.display.value;
+
+                if (shouldShow)
+                {
+                    element.style.display = DisplayStyle.Flex;
+                    UpdateBuildingNameDisplay(element, correspondingTypes[i]);
+                    Debug.Log($"UI Element {allShopElements[i]} ({correspondingTypes[i]}): SHOWING (was {previousDisplay})");
+                }
+                else
+                {
+                    element.style.display = DisplayStyle.None;
+                    Debug.Log($"UI Element {allShopElements[i]} ({correspondingTypes[i]}): HIDING (was {previousDisplay})");
+                }
+            }
+            else
+            {
+                Debug.LogWarning($"UI Element {allShopElements[i]} not found in root element!");
+            }
+        }
+
+        // Handle Harbor visibility based on settlement context
+        var harborElement = rootElement.Q<VisualElement>("Harbor");
+        if (harborElement != null)
+        {
+            bool shouldShowHarbor = true; // Default to show
+
+            if (SettlementContext.Instance != null)
+            {
+                shouldShowHarbor = SettlementContext.Instance.hasHarbor;
+                Debug.Log($"Harbor visibility: {shouldShowHarbor} (hasHarbor: {SettlementContext.Instance.hasHarbor})");
+            }
+
+            harborElement.style.display = shouldShowHarbor ? DisplayStyle.Flex : DisplayStyle.None;
+        }
+    }
+
+    private void UpdateAllBuildingNames()
+    {
+        if (rootElement == null) return;
+
+        var allShopElements = new string[] { "WeaponShop", "ArmorShop", "PotionShop", "GeneralStore" };
+        var correspondingTypes = new ShopType[] { ShopType.Weapons, ShopType.Armor, ShopType.Potions, ShopType.General };
+
+        for (int i = 0; i < allShopElements.Length; i++)
+        {
+            var element = rootElement.Q<VisualElement>(allShopElements[i]);
+            if (element != null)
+            {
+                UpdateBuildingNameDisplay(element, correspondingTypes[i]);
+            }
+        }
+
+        Debug.Log("Updated all building names to match shop data");
+    }
+
+    private void UpdateBuildingNameDisplay(VisualElement buildingElement, ShopType shopType)
+    {
+        // Check if allShops is available
+        if (allShops == null || allShops.Length == 0)
+        {
+            Debug.LogWarning($"UpdateBuildingNameDisplay: allShops is null or empty for {shopType}");
+            return;
+        }
+
+        // Find the shop with this type
+        var shop = allShops.FirstOrDefault(s => s != null && s.shopType == shopType && s.gameObject.activeInHierarchy);
+        if (shop == null) return;
+
+        // Look for various possible label elements that might contain the building name
+        var possibleLabelSelectors = new string[]
+        {
+            "building-name",
+            "shop-name",
+            "label",
+            "name-label",
+            "title"
+        };
+
+        bool nameUpdated = false;
+        foreach (var selector in possibleLabelSelectors)
+        {
+            var nameLabel = buildingElement.Q<Label>(selector);
+            if (nameLabel != null)
+            {
+                string oldText = nameLabel.text;
+                nameLabel.text = shop.buildingName;
+                Debug.Log($"Updated building display name: {selector} '{oldText}' -> '{shop.buildingName}'");
+                nameUpdated = true;
+                break;
+            }
+        }
+
+        // Try to find any Label element within the building element
+        if (!nameUpdated)
+        {
+            var allLabels = buildingElement.Query<Label>().ToList();
+            foreach (var label in allLabels)
+            {
+                // Skip if label text looks like it might be something else (like "WEAPONS", "ARMOR", etc)
+                if (!string.IsNullOrEmpty(label.text) &&
+                    !label.text.ToUpper().Contains("WEAPON") &&
+                    !label.text.ToUpper().Contains("ARMOR") &&
+                    !label.text.ToUpper().Contains("POTION") &&
+                    !label.text.ToUpper().Contains("GENERAL"))
+                {
+                    string oldText = label.text;
+                    label.text = shop.buildingName;
+                    Debug.Log($"Updated building label: '{oldText}' -> '{shop.buildingName}'");
+                    nameUpdated = true;
+                    break;
+                }
+            }
+        }
+
+        // If still no update, log the building structure for debugging
+        if (!nameUpdated)
+        {
+            Debug.Log($"Could not find name label for {shopType} building (shop: {shop.buildingName})");
+            LogBuildingStructure(buildingElement, shopType);
+        }
+    }
+
+    private void LogBuildingStructure(VisualElement buildingElement, ShopType shopType)
+    {
+        Debug.Log($"=== Building Structure for {shopType} ===");
+        Debug.Log($"Element name: {buildingElement.name}");
+
+        var labels = buildingElement.Query<Label>().ToList();
+        Debug.Log($"Found {labels.Count} labels:");
+        for (int i = 0; i < labels.Count; i++)
+        {
+            Debug.Log($"  Label {i}: name='{labels[i].name}', text='{labels[i].text}'");
+        }
+    }
+
+    private string GetUIElementNameForShop(TownShop shop)
+    {
+        switch (shop.shopType)
+        {
+            case ShopType.Weapons: return "WeaponShop";
+            case ShopType.Armor: return "ArmorShop";
+            case ShopType.Potions: return "PotionShop";
+            case ShopType.General: return "GeneralStore";
+            default: return shop.buildingName.Replace(" ", "");
+        }
+    }
+
+    private void SetupUIClickHandlers()
+    {
+        if (townUI == null)
+        {
+            Debug.LogError("TownUI is null!");
+            return;
+        }
+
+        rootElement = townUI.rootVisualElement;
+
+        if (rootElement == null)
+        {
+            Debug.LogError("Root element is null!");
+            return;
+        }
+
+        Debug.Log($"Setting up click handlers for {shopLookup.Count} shops");
+
+        // Setup click handlers for each shop
+        foreach (var kvp in shopLookup)
+        {
+            var shopElement = rootElement.Q<VisualElement>(kvp.Key);
+            if (shopElement != null)
+            {
+                // Create and store the callback so we can unregister it later
+                var shop = kvp.Value;
+                EventCallback<ClickEvent> callback = evt => OnShopClicked(shop);
+
+                // Store the callback for later cleanup
+                clickCallbacks[kvp.Key] = callback;
+
+                // Register the callback
+                shopElement.RegisterCallback<ClickEvent>(callback);
+
+                // Add visual feedback for interactable elements
+                shopElement.AddToClassList("interactable-building");
+
+                Debug.Log($"✓ Setup click handler for {kvp.Key} -> {shop.buildingName}");
+            }
+            else
+            {
+                Debug.LogWarning($"✗ Could not find UI element: {kvp.Key}");
+
+                // List all available elements for debugging
+                DebugListChildElements(rootElement, kvp.Key);
+            }
+        }
+
+        // Setup other building click handlers
+        SetupSpecialBuildingHandlers();
+    }
+
+    private void DebugListChildElements(VisualElement parent, string searchName)
+    {
+        Debug.Log($"Looking for '{searchName}' in available elements:");
+        foreach (var child in parent.Children())
+        {
+            Debug.Log($"  - Found element: {child.name} (type: {child.GetType().Name})");
+            if (child.childCount > 0)
+            {
+                DebugListChildElementsRecursive(child, 1);
+            }
+        }
+    }
+
+    private void DebugListChildElementsRecursive(VisualElement parent, int depth)
+    {
+        string indent = new string(' ', depth * 4);
+        foreach (var child in parent.Children())
+        {
+            Debug.Log($"{indent}- {child.name} (type: {child.GetType().Name})");
+            if (child.childCount > 0 && depth < 3) // Limit recursion
+            {
+                DebugListChildElementsRecursive(child, depth + 1);
+            }
+        }
+    }
+
+    // This method handles all shop clicks to avoid closure issues
+    private void OnAnyShopClicked(ClickEvent evt)
+    {
+        var element = evt.target as VisualElement;
+        if (element != null && shopLookup.ContainsKey(element.name))
+        {
+            OnShopClicked(shopLookup[element.name]);
+        }
+    }
+
+    private void SetupSpecialBuildingHandlers()
+    {
+        // Adventurer's Guild
+        var guild = rootElement.Q<VisualElement>("AdventurersGuild");
+        if (guild != null)
+        {
+            guild.RegisterCallback<ClickEvent>(evt => OnAdventurersGuildClicked());
+            guild.AddToClassList("interactable-building");
+            Debug.Log("✓ Setup Adventurer's Guild click handler");
+        }
+        else
+        {
+            Debug.LogWarning("✗ Could not find AdventurersGuild element");
+        }
+
+        // Harbor
+        var harbor = rootElement.Q<VisualElement>("Harbor");
+        if (harbor != null)
+        {
+            harbor.RegisterCallback<ClickEvent>(evt => OnHarborClicked());
+            harbor.AddToClassList("interactable-building");
+            Debug.Log("✓ Setup Harbor click handler");
+        }
+        else
+        {
+            Debug.LogWarning("✗ Could not find Harbor element");
+        }
+
+        // Inn
+        var inn = rootElement.Q<VisualElement>("Inn");
+        if (inn != null)
+        {
+            inn.RegisterCallback<ClickEvent>(evt => OnInnClicked());
+            inn.AddToClassList("interactable-building");
+            Debug.Log("✓ Setup Inn click handler");
+        }
+        else
+        {
+            Debug.LogWarning("✗ Could not find Inn element");
+        }
+
+        // Map button
+        var mapButton = rootElement.Q<Button>("MapButton");
+        if (mapButton != null)
+        {
+            mapButton.clicked += OnReturnToMapClicked;
+            Debug.Log("✓ Setup Map button click handler");
+        }
+        else
+        {
+            Debug.LogWarning("✗ Could not find MapButton element");
+        }
+
+        // Inventory button
+        var inventoryButton = rootElement.Q<Button>("InventoryButton");
+        if (inventoryButton != null)
+        {
+            inventoryButton.clicked += OnInventoryClicked;
+            Debug.Log("✓ Setup Inventory button click handler");
+        }
+        else
+        {
+            Debug.LogWarning("✗ Could not find InventoryButton element");
+        }
+    }
+
+    private void OnShopClicked(TownShop shop)
+    {
+        // Prevent multiple shop UIs from opening simultaneously
+        if (isShopUIOpen)
+        {
+            Debug.Log($"Shop UI already open, ignoring click on {shop.buildingName}");
+            return;
+        }
+
+        Debug.Log($"=== SHOP CLICK DEBUG ===");
+        Debug.Log($"Clicked shop: {shop.buildingName} ({shop.shopType})");
+        Debug.Log($"Shop keeper: {shop.shopkeeperName}");
+        Debug.Log($"GameObject name: {shop.gameObject.name}");
+        Debug.Log($"=== Opening shop UI ===");
+
+        // Handle shop opening directly in TownShopManager
+        // Don't delegate to TownManager to avoid duplicate UI creation
+        OpenShopUI(shop);
+    }
+
+    private void OpenShopUI(TownShop shop)
+    {
+        // Set flag to prevent multiple openings
+        isShopUIOpen = true;
+
+        // Close any existing shop UIs first
+        var existingShopUIs = FindObjectsByType<TownShopUI>(FindObjectsSortMode.None);
+        foreach (var existingUI in existingShopUIs)
+        {
+            if (existingUI.gameObject != null)
+            {
+                Debug.Log($"Closing existing shop UI: {existingUI.gameObject.name}");
+                Destroy(existingUI.gameObject);
+            }
+        }
+
+        // Create shop UI GameObject as a separate top-level object
+        var shopUIObject = new GameObject("TownShopUI");
+
+        // Add UIDocument component and load the UXML
+        var uiDocument = shopUIObject.AddComponent<UIDocument>();
+
+        // Copy settings from town UI document if available
+        if (townUI != null)
+        {
+            uiDocument.panelSettings = townUI.panelSettings;
+            uiDocument.sortingOrder = townUI.sortingOrder + 100; // Ensure it's on top
+        }
+
+        uiDocument.visualTreeAsset = Resources.Load<VisualTreeAsset>("UI/TownShopUI");
+
+        Debug.Log($"Loaded UXML asset: {uiDocument.visualTreeAsset != null}");
+
+        // If not found in Resources, try direct path
+        if (uiDocument.visualTreeAsset == null)
+        {
+#if UNITY_EDITOR
+            uiDocument.visualTreeAsset = UnityEditor.AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/TownShopUI.uxml");
+            Debug.Log($"Loaded UXML from Assets: {uiDocument.visualTreeAsset != null}");
+#endif
+        }
+
+        if (uiDocument.visualTreeAsset == null)
+        {
+            Debug.LogError("Failed to load TownShopUI UXML!");
+            Destroy(shopUIObject);
+            return;
+        }
+
+        // Add TownShopUI component 
+        var shopUI = shopUIObject.AddComponent<TownShopUI>();
+
+        // Set the UI document reference
+        shopUI.uiDocument = uiDocument;
+
+        // Wait for proper initialization then set shop data
+        StartCoroutine(InitializeShopUIDelayed(shopUI, shop));
+
+        // Reset flag when this specific shop UI is destroyed
+        StartCoroutine(WatchForShopUIDestruction(shopUIObject));
+
+        Debug.Log($"Opened shop UI for {shop.buildingName} with sortOrder: {uiDocument.sortingOrder}");
+    }
+
+    private System.Collections.IEnumerator InitializeShopUIDelayed(TownShopUI shopUI, TownShop shop)
+    {
+        // Wait a frame to ensure Start() is called
+        yield return null;
+
+        // Now set the shop data and open
+        shopUI.SetShop(shop);
+        shopUI.OpenShop();
+
+        Debug.Log($"Shop UI initialization completed for {shop.buildingName}");
+    }
+
+    private System.Collections.IEnumerator WatchForShopUIDestruction(GameObject shopUIObject)
+    {
+        while (shopUIObject != null)
+        {
+            yield return null;
+        }
+
+        // Shop UI was destroyed, reset flag
+        isShopUIOpen = false;
+        Debug.Log("Shop UI closed - ready for new shop");
+    }
+
+    private void OnAdventurersGuildClicked()
+    {
+        Debug.Log("Adventurer's Guild clicked - Quest system not implemented yet");
+        ShowNotImplementedMessage("Adventurer's Guild", "Quest and job board system");
+    }
+
+    private void OnHarborClicked()
+    {
+        Debug.Log("Harbor clicked - Travel system not implemented yet");
+        ShowNotImplementedMessage("Harbor", "Sea travel and shipping");
+    }
+
+    private void OnInnClicked()
+    {
+        Debug.Log("Inn clicked - Rest system not implemented yet");
+        ShowNotImplementedMessage("The Wanderer's Rest", "Rest, heal, and save progress");
+    }
+
+    private void OnReturnToMapClicked()
+    {
+        Debug.Log("Returning to map");
+        UnityEngine.SceneManagement.SceneManager.LoadScene("MapScene2");
+    }
+
+    private void OnInventoryClicked()
+    {
+        Debug.Log("Team inventory clicked - not implemented yet");
+        ShowNotImplementedMessage("Team Inventory", "View and manage party equipment");
+    }
+
+    private void ShowNotImplementedMessage(string buildingName, string description)
+    {
+        // Create a simple popup message
+        var popup = new VisualElement();
+        popup.style.position = Position.Absolute;
+        popup.style.width = Length.Percent(100);
+        popup.style.height = Length.Percent(100);
+        popup.style.backgroundColor = new Color(0, 0, 0, 0.7f);
+        popup.style.justifyContent = Justify.Center;
+        popup.style.alignItems = Align.Center;
+
+        var messageBox = new VisualElement();
+        messageBox.style.width = 400;
+        messageBox.style.height = 200;
+        messageBox.style.backgroundColor = new Color(0.9f, 0.9f, 0.9f);
+        messageBox.style.borderLeftWidth = 2;
+        messageBox.style.borderRightWidth = 2;
+        messageBox.style.borderTopWidth = 2;
+        messageBox.style.borderBottomWidth = 2;
+        messageBox.style.borderLeftColor = Color.black;
+        messageBox.style.borderRightColor = Color.black;
+        messageBox.style.borderTopColor = Color.black;
+        messageBox.style.borderBottomColor = Color.black;
+        messageBox.style.borderTopLeftRadius = 10;
+        messageBox.style.borderTopRightRadius = 10;
+        messageBox.style.borderBottomLeftRadius = 10;
+        messageBox.style.borderBottomRightRadius = 10;
+        messageBox.style.paddingLeft = 20;
+        messageBox.style.paddingRight = 20;
+        messageBox.style.paddingTop = 20;
+        messageBox.style.paddingBottom = 20;
+        messageBox.style.justifyContent = Justify.Center;
+        messageBox.style.alignItems = Align.Center;
+
+        var titleLabel = new Label(buildingName);
+        titleLabel.style.fontSize = 20;
+        titleLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
+        titleLabel.style.color = Color.black;
+        titleLabel.style.marginBottom = 10;
+
+        var descLabel = new Label($"Coming Soon!\n\n{description}");
+        descLabel.style.fontSize = 14;
+        descLabel.style.color = new Color(0.3f, 0.3f, 0.3f);
+        descLabel.style.whiteSpace = WhiteSpace.Normal;
+        descLabel.style.unityTextAlign = TextAnchor.MiddleCenter;
+        descLabel.style.marginBottom = 20;
+
+        var closeButton = new Button { text = "Close" };
+        closeButton.style.width = 100;
+        closeButton.style.height = 30;
+        closeButton.clicked += () => rootElement.Remove(popup);
+
+        messageBox.Add(titleLabel);
+        messageBox.Add(descLabel);
+        messageBox.Add(closeButton);
+        popup.Add(messageBox);
+
+        rootElement.Add(popup);
+
+        // Auto-close after 3 seconds
+        StartCoroutine(ClosePopupAfterDelay(popup, 3f));
+    }
+
+    private System.Collections.IEnumerator ClosePopupAfterDelay(VisualElement popup, float delay)
+    {
+        yield return new WaitForSeconds(delay);
+        if (popup.parent != null)
+            rootElement.Remove(popup);
+    }
+
+    public void UpdateMoneyDisplay()
+    {
+        var moneyAmount = rootElement?.Q<Label>("MoneyAmount");
+        if (moneyAmount != null)
+        {
+            var townManager = FindFirstObjectByType<TownManager>();
+            if (townManager?.currentTeam?[0] != null)
+            {
+                var character = townManager.currentTeam[0];
+                string moneyText = "";
+                if (character.gold > 0) moneyText += $"{character.gold}g ";
+                if (character.silver > 0) moneyText += $"{character.silver}s ";
+                if (character.copper > 0) moneyText += $"{character.copper}c";
+
+                moneyAmount.text = moneyText.Trim();
+            }
+        }
+    }
+
+    void Update()
+    {
+        // Update money display periodically (could be optimized with events)
+        if (Time.frameCount % 60 == 0) // Update once per second at 60fps
+        {
+            UpdateMoneyDisplay();
+        }
+    }
+}

+ 778 - 0
Assets/Scripts/Town/TownShopUI.cs

@@ -0,0 +1,778 @@
+using System.Collections.Generic;
+using UnityEngine;
+using UnityEngine.UIElements;
+
+public class TownShopUI : MonoBehaviour
+{
+    [Header("References")]
+    public UIDocument uiDocument;
+
+    [Header("Shop Settings")]
+    public TownShop currentShop;
+    public TeamCharacter selectedCustomer;
+
+    // UI Elements
+    private VisualElement root;
+    private VisualElement shopContainer;
+    private Label shopNameLabel;
+    private Label shopkeeperLabel;
+    private VisualElement itemList;
+    private VisualElement customerPanel;
+    private DropdownField customerDropdown;
+    private Label moneyLabel;
+    private VisualElement tabContainer;
+    private Button buyTab;
+    private Button sellTab;
+    private DropdownField categoryFilter;
+    private TextField searchField;
+    private Button closeButton;
+
+    // State
+    private bool isSellMode = false;
+
+    private void Start()
+    {
+        InitializeUI();
+        SetupEventHandlers();
+
+        // Try to load team from GameStateManager
+        if (GameStateManager.Instance?.savedTeam != null)
+        {
+            foreach (var character in GameStateManager.Instance.savedTeam)
+            {
+                if (character != null)
+                {
+                    selectedCustomer = character;
+                    UpdateCustomerDisplay();
+                    break;
+                }
+            }
+        }
+    }
+
+    public void SetShop(TownShop shop)
+    {
+        Debug.Log($"=== TownShopUI.SetShop DEBUG ===");
+        Debug.Log($"Received shop: {shop?.buildingName ?? "NULL"} ({shop?.shopType})");
+        Debug.Log($"Shop keeper: {shop?.shopkeeperName ?? "NULL"}");
+        Debug.Log($"Current shop before: {currentShop?.buildingName ?? "NULL"}");
+
+        currentShop = shop;
+
+        Debug.Log($"Current shop after: {currentShop?.buildingName ?? "NULL"}");
+
+        if (root != null)
+        {
+            UpdateShopDisplay();
+            RefreshItemList();
+        }
+    }
+
+    public void SetCustomer(TeamCharacter customer)
+    {
+        selectedCustomer = customer;
+        UpdateCustomerDisplay();
+        RefreshItemList();
+    }
+
+    private void InitializeUI()
+    {
+        if (uiDocument == null)
+        {
+            uiDocument = GetComponent<UIDocument>();
+        }
+
+        if (uiDocument?.rootVisualElement == null)
+        {
+            Debug.LogError("UI Document or root visual element is null!");
+            return;
+        }
+
+        // Force refresh the UI Document to ensure proper initialization
+        uiDocument.enabled = false;
+        uiDocument.enabled = true;
+
+        root = uiDocument.rootVisualElement;
+        Debug.Log($"Root element found: {root != null}");
+
+        // Ensure root element is visible and properly configured
+        if (root != null)
+        {
+            root.style.position = Position.Absolute;
+            root.style.left = 0;
+            root.style.top = 0;
+            root.style.right = 0;
+            root.style.bottom = 0;
+            root.style.visibility = Visibility.Visible;
+            root.style.display = DisplayStyle.Flex;
+            Debug.Log("Root element visibility and position configured");
+        }
+
+        // Get UI elements
+        shopContainer = root.Q<VisualElement>("shop-container");
+        shopNameLabel = root.Q<Label>("shop-name");
+        shopkeeperLabel = root.Q<Label>("shopkeeper-name");
+        itemList = root.Q<VisualElement>("item-list");
+        customerPanel = root.Q<VisualElement>("customer-panel");
+        customerDropdown = root.Q<DropdownField>("customer-dropdown");
+        moneyLabel = root.Q<Label>("money-label");
+        tabContainer = root.Q<VisualElement>("tab-container");
+        buyTab = root.Q<Button>("buy-tab");
+        sellTab = root.Q<Button>("sell-tab");
+        categoryFilter = root.Q<DropdownField>("category-filter");
+        searchField = root.Q<TextField>("search-field");
+        closeButton = root.Q<Button>("close-button");
+
+        Debug.Log($"Key UI elements found - shopContainer: {shopContainer != null}, shopNameLabel: {shopNameLabel != null}, buyTab: {buyTab != null}");
+
+        // Set initial visibility
+        if (shopContainer != null)
+        {
+            shopContainer.style.display = DisplayStyle.None;
+            Debug.Log("Set shopContainer to hidden initially");
+        }
+        else
+        {
+            Debug.LogError("shopContainer not found! Check UXML element names.");
+        }
+
+        // Setup category filter options
+        if (categoryFilter != null)
+        {
+            categoryFilter.choices = new List<string> { "All", "Weapons", "Armor", "Potions", "Misc" };
+            categoryFilter.value = "All";
+        }
+
+        Debug.Log("TownShopUI initialized");
+    }
+
+    private void SetupEventHandlers()
+    {
+        if (buyTab != null)
+        {
+            buyTab.clicked += SwitchToBuyMode;
+        }
+
+        if (sellTab != null)
+        {
+            sellTab.clicked += SwitchToSellMode;
+        }
+
+        if (closeButton != null)
+        {
+            closeButton.clicked += CloseShop;
+        }
+
+        if (customerDropdown != null)
+        {
+            customerDropdown.RegisterValueChangedCallback(OnCustomerChanged);
+        }
+
+        if (categoryFilter != null)
+        {
+            categoryFilter.RegisterValueChangedCallback(evt => RefreshItemList());
+        }
+
+        if (searchField != null)
+        {
+            searchField.RegisterValueChangedCallback(evt => RefreshItemList());
+        }
+    }
+
+    public void OpenShop()
+    {
+        Debug.Log($"=== OpenShop called ===");
+        Debug.Log($"shopContainer: {shopContainer != null}");
+        Debug.Log($"currentShop: {currentShop?.buildingName ?? "NULL"}");
+
+        if (shopContainer != null)
+        {
+            shopContainer.style.display = DisplayStyle.Flex;
+            Debug.Log("Set shopContainer to visible");
+        }
+        else
+        {
+            Debug.LogError("Cannot open shop - shopContainer is null! Creating fallback UI...");
+            CreateFallbackUI();
+            return;
+        }
+
+        PopulateCustomerDropdown();
+        UpdateShopDisplay();
+        UpdateCustomerDisplay();
+        SwitchToBuyMode();
+        RefreshItemList();
+
+        Debug.Log("Shop opening sequence completed");
+    }
+
+    private void CreateFallbackUI()
+    {
+        if (root == null) return;
+
+        // Create a simple fallback UI directly in code
+        var fallbackContainer = new VisualElement();
+        fallbackContainer.style.position = Position.Absolute;
+        fallbackContainer.style.width = Length.Percent(100);
+        fallbackContainer.style.height = Length.Percent(100);
+        fallbackContainer.style.backgroundColor = new Color(0, 0, 0, 0.8f);
+        fallbackContainer.style.justifyContent = Justify.Center;
+        fallbackContainer.style.alignItems = Align.Center;
+
+        var shopWindow = new VisualElement();
+        shopWindow.style.width = 400;
+        shopWindow.style.height = 300;
+        shopWindow.style.backgroundColor = new Color(0.9f, 0.85f, 0.7f);
+        shopWindow.style.borderLeftWidth = 3;
+        shopWindow.style.borderRightWidth = 3;
+        shopWindow.style.borderTopWidth = 3;
+        shopWindow.style.borderBottomWidth = 3;
+        shopWindow.style.borderLeftColor = new Color(0.55f, 0.27f, 0.07f);
+        shopWindow.style.borderRightColor = new Color(0.55f, 0.27f, 0.07f);
+        shopWindow.style.borderTopColor = new Color(0.55f, 0.27f, 0.07f);
+        shopWindow.style.borderBottomColor = new Color(0.55f, 0.27f, 0.07f);
+        shopWindow.style.borderTopLeftRadius = 10;
+        shopWindow.style.borderTopRightRadius = 10;
+        shopWindow.style.borderBottomLeftRadius = 10;
+        shopWindow.style.borderBottomRightRadius = 10;
+        shopWindow.style.paddingLeft = 20;
+        shopWindow.style.paddingRight = 20;
+        shopWindow.style.paddingTop = 20;
+        shopWindow.style.paddingBottom = 20;
+
+        var title = new Label($"{currentShop?.buildingName ?? "Shop"} - FALLBACK UI");
+        title.style.fontSize = 20;
+        title.style.color = new Color(0.55f, 0.27f, 0.07f);
+        title.style.unityFontStyleAndWeight = FontStyle.Bold;
+        title.style.marginBottom = 20;
+
+        var message = new Label("The full shop UI failed to load.\nThis is a simplified fallback interface.\nCheck console for details.");
+        message.style.fontSize = 14;
+        message.style.color = new Color(0.3f, 0.3f, 0.3f);
+        message.style.whiteSpace = WhiteSpace.Normal;
+        message.style.marginBottom = 20;
+
+        var closeButton = new Button(() =>
+        {
+            root.Remove(fallbackContainer);
+            Destroy(gameObject);
+        });
+        closeButton.text = "Close";
+        closeButton.style.backgroundColor = new Color(0.8f, 0.2f, 0.2f);
+        closeButton.style.color = Color.white;
+        closeButton.style.borderLeftWidth = 0;
+        closeButton.style.borderRightWidth = 0;
+        closeButton.style.borderTopWidth = 0;
+        closeButton.style.borderBottomWidth = 0;
+        closeButton.style.borderTopLeftRadius = 5;
+        closeButton.style.borderTopRightRadius = 5;
+        closeButton.style.borderBottomLeftRadius = 5;
+        closeButton.style.borderBottomRightRadius = 5;
+        closeButton.style.width = 80;
+        closeButton.style.height = 30;
+
+        shopWindow.Add(title);
+        shopWindow.Add(message);
+        shopWindow.Add(closeButton);
+        fallbackContainer.Add(shopWindow);
+        root.Add(fallbackContainer);
+
+        Debug.Log("Fallback UI created and displayed");
+    }
+
+    private void CloseShop()
+    {
+        if (shopContainer != null)
+        {
+            shopContainer.style.display = DisplayStyle.None;
+        }
+
+        // Destroy the entire shop UI GameObject
+        Destroy(gameObject);
+        Debug.Log("Shop UI closed and destroyed");
+    }
+
+    private void PopulateCustomerDropdown()
+    {
+        if (customerDropdown == null || GameStateManager.Instance?.savedTeam == null) return;
+
+        var choices = new List<string>();
+        foreach (var member in GameStateManager.Instance.savedTeam)
+        {
+            if (member != null)
+            {
+                choices.Add(member.name); // Using correct property name
+            }
+        }
+
+        customerDropdown.choices = choices;
+        if (choices.Count > 0)
+        {
+            customerDropdown.value = choices[0];
+            if (selectedCustomer == null)
+            {
+                foreach (var member in GameStateManager.Instance.savedTeam)
+                {
+                    if (member != null)
+                    {
+                        selectedCustomer = member;
+                        break;
+                    }
+                }
+            }
+        }
+    }
+
+    private void OnCustomerChanged(ChangeEvent<string> evt)
+    {
+        if (GameStateManager.Instance?.savedTeam == null) return;
+
+        foreach (var member in GameStateManager.Instance.savedTeam)
+        {
+            if (member != null && member.name == evt.newValue) // Using correct property name
+            {
+                selectedCustomer = member;
+                UpdateCustomerDisplay();
+                RefreshItemList();
+                break;
+            }
+        }
+    }
+
+    private void UpdateShopDisplay()
+    {
+        Debug.Log($"=== UpdateShopDisplay DEBUG ===");
+        Debug.Log($"Current shop: {currentShop?.buildingName ?? "NULL"} ({currentShop?.shopType})");
+        Debug.Log($"shopNameLabel: {shopNameLabel != null}");
+        Debug.Log($"shopkeeperLabel: {shopkeeperLabel != null}");
+
+        if (currentShop == null) return;
+
+        if (shopNameLabel != null)
+        {
+            shopNameLabel.text = currentShop.buildingName;
+            Debug.Log($"Set shop name label to: {currentShop.buildingName}");
+        }
+
+        if (shopkeeperLabel != null)
+        {
+            shopkeeperLabel.text = $"Shopkeeper: {currentShop.shopkeeperName}";
+            Debug.Log($"Set shopkeeper label to: {currentShop.shopkeeperName}");
+        }
+    }
+
+    private void UpdateCustomerDisplay()
+    {
+        if (selectedCustomer == null) return;
+
+        UpdateMoneyDisplay();
+    }
+
+    private void UpdateMoneyDisplay()
+    {
+        if (moneyLabel == null || selectedCustomer == null) return;
+
+        moneyLabel.text = $"Money: {selectedCustomer.gold}g {selectedCustomer.silver}s {selectedCustomer.copper}c";
+    }
+
+    private void RefreshItemList()
+    {
+        if (itemList == null || currentShop == null) return;
+
+        itemList.Clear();
+
+        if (isSellMode)
+        {
+            // Show player inventory for selling
+            PopulateSellItems();
+        }
+        else
+        {
+            // Show shop inventory for buying
+            PopulateBuyItems();
+        }
+    }
+
+    private void PopulateBuyItems()
+    {
+        // Get shop inventory using the correct method
+        var shopInventory = currentShop.GetInventory();
+
+        foreach (var shopItem in shopInventory)
+        {
+            if (shopItem == null || shopItem.item == null) continue;
+
+            // Apply filters
+            string searchText = searchField?.value?.ToLower() ?? "";
+            string selectedCategory = categoryFilter?.value ?? "All";
+
+            if (!string.IsNullOrEmpty(searchText) && !shopItem.item.itemName.ToLower().Contains(searchText))
+                continue;
+
+            if (selectedCategory != "All" && !MatchesCategory(shopItem.item, selectedCategory))
+                continue;
+
+            CreateShopItemElement(shopItem);
+        }
+    }
+
+    private void PopulateSellItems()
+    {
+        if (selectedCustomer == null) return;
+
+        // Get player's inventory items using correct property names
+        var playerItems = GetPlayerInventoryItems();
+        foreach (var item in playerItems)
+        {
+            if (item == null) continue;
+
+            // Apply filters
+            string searchText = searchField?.value?.ToLower() ?? "";
+            string selectedCategory = categoryFilter?.value ?? "All";
+
+            if (!string.IsNullOrEmpty(searchText) && !item.itemName.ToLower().Contains(searchText))
+                continue;
+
+            if (selectedCategory != "All" && !MatchesCategory(item, selectedCategory))
+                continue;
+
+            CreateSellItemElement(item);
+        }
+    }
+
+    private List<Item> GetPlayerInventoryItems()
+    {
+        var items = new List<Item>();
+
+        if (selectedCustomer == null) return items;
+
+        // Note: TeamCharacter stores item names as strings, but we need actual Item objects
+        // This is a limitation of the current system - we would need an ItemDatabase
+        // to convert item names back to Item objects for proper selling functionality
+
+        // For now, return empty list with a debug message
+        if (selectedCustomer.weapons != null && selectedCustomer.weapons.Count > 0)
+        {
+            Debug.LogWarning("Player has weapons but cannot display them - need ItemDatabase to convert string names to Item objects");
+        }
+
+        if (selectedCustomer.armor != null && selectedCustomer.armor.Count > 0)
+        {
+            Debug.LogWarning("Player has armor but cannot display them - need ItemDatabase to convert string names to Item objects");
+        }
+
+        if (selectedCustomer.miscItems != null && selectedCustomer.miscItems.Count > 0)
+        {
+            Debug.LogWarning("Player has misc items but cannot display them - need ItemDatabase to convert string names to Item objects");
+        }
+
+        return items;
+    }
+
+    private bool MatchesCategory(Item item, string category)
+    {
+        switch (category)
+        {
+            case "Weapons": return item is WeaponItem;
+            case "Armor": return item is ArmorItem;
+            case "Potions": return item is MiscellaneousItem && item.itemType == ItemType.Consumable;
+            case "Misc": return item is MiscellaneousItem;
+            default: return true;
+        }
+    }
+
+    private void CreateShopItemElement(ShopInventoryItem shopItem)
+    {
+        var itemElement = new VisualElement();
+        itemElement.AddToClassList("shop-item");
+
+        // Use flexible row layout
+        itemElement.style.flexDirection = FlexDirection.Row;
+        itemElement.style.alignItems = Align.Center;
+        itemElement.style.justifyContent = Justify.SpaceBetween;
+        itemElement.style.paddingTop = 5;
+        itemElement.style.paddingBottom = 5;
+        itemElement.style.paddingLeft = 10;
+        itemElement.style.paddingRight = 10;
+        itemElement.style.marginBottom = 3;
+        itemElement.style.backgroundColor = new Color(0.95f, 0.95f, 0.95f, 1f);
+        itemElement.style.borderBottomWidth = 1;
+        itemElement.style.borderBottomColor = new Color(0.8f, 0.8f, 0.8f, 1f);
+
+        // Left side - Item info container
+        var infoContainer = new VisualElement();
+        infoContainer.style.flexDirection = FlexDirection.Column;
+        infoContainer.style.flexGrow = 1;
+        infoContainer.style.marginRight = 10;
+
+        var nameLabel = new Label(shopItem.item.itemName);
+        nameLabel.AddToClassList("item-name");
+        nameLabel.style.fontSize = 14;
+        nameLabel.style.color = new Color(0.2f, 0.2f, 0.2f, 1f);
+        nameLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
+
+        var descLabel = new Label(shopItem.item.description);
+        descLabel.AddToClassList("item-description");
+        descLabel.style.fontSize = 12;
+        descLabel.style.color = new Color(0.4f, 0.4f, 0.4f, 1f);
+        descLabel.style.whiteSpace = WhiteSpace.Normal;
+
+        infoContainer.Add(nameLabel);
+        infoContainer.Add(descLabel);
+
+        // Right side - Price and button container
+        var actionContainer = new VisualElement();
+        actionContainer.style.flexDirection = FlexDirection.Row;
+        actionContainer.style.alignItems = Align.Center;
+        actionContainer.style.minWidth = 150;
+
+        var priceLabel = new Label(shopItem.GetPriceString());
+        priceLabel.AddToClassList("item-price");
+        priceLabel.style.fontSize = 12;
+        priceLabel.style.color = new Color(0.0f, 0.5f, 0.0f, 1f);
+        priceLabel.style.marginRight = 10;
+        priceLabel.style.minWidth = 60;
+
+        var buyButton = new Button(() => BuyItem(shopItem))
+        {
+            text = "Buy"
+        };
+        buyButton.AddToClassList("buy-button");
+        buyButton.style.width = 60;
+        buyButton.style.height = 25;
+        buyButton.style.fontSize = 12;
+
+        // Check if customer can afford
+        if (selectedCustomer != null && !shopItem.CanAfford(selectedCustomer))
+        {
+            buyButton.SetEnabled(false);
+            priceLabel.style.color = new Color(0.8f, 0.2f, 0.2f, 1f);
+        }
+
+        actionContainer.Add(priceLabel);
+        actionContainer.Add(buyButton);
+
+        itemElement.Add(infoContainer);
+        itemElement.Add(actionContainer);
+
+        itemList.Add(itemElement);
+    }
+
+    private void CreateSellItemElement(Item item)
+    {
+        var itemElement = new VisualElement();
+        itemElement.AddToClassList("sell-item");
+
+        // Use flexible row layout
+        itemElement.style.flexDirection = FlexDirection.Row;
+        itemElement.style.alignItems = Align.Center;
+        itemElement.style.justifyContent = Justify.SpaceBetween;
+        itemElement.style.paddingTop = 5;
+        itemElement.style.paddingBottom = 5;
+        itemElement.style.paddingLeft = 10;
+        itemElement.style.paddingRight = 10;
+        itemElement.style.marginBottom = 3;
+        itemElement.style.backgroundColor = new Color(0.95f, 0.95f, 0.95f, 1f);
+        itemElement.style.borderBottomWidth = 1;
+        itemElement.style.borderBottomColor = new Color(0.8f, 0.8f, 0.8f, 1f);
+
+        // Left side - Item info container
+        var infoContainer = new VisualElement();
+        infoContainer.style.flexDirection = FlexDirection.Column;
+        infoContainer.style.flexGrow = 1;
+        infoContainer.style.marginRight = 10;
+
+        var nameLabel = new Label(item.itemName);
+        nameLabel.AddToClassList("item-name");
+        nameLabel.style.fontSize = 14;
+        nameLabel.style.color = new Color(0.2f, 0.2f, 0.2f, 1f);
+        nameLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
+
+        var descLabel = new Label(item.description);
+        descLabel.AddToClassList("item-description");
+        descLabel.style.fontSize = 12;
+        descLabel.style.color = new Color(0.4f, 0.4f, 0.4f, 1f);
+        descLabel.style.whiteSpace = WhiteSpace.Normal;
+
+        infoContainer.Add(nameLabel);
+        infoContainer.Add(descLabel);
+
+        // Right side - Price and button container
+        var actionContainer = new VisualElement();
+        actionContainer.style.flexDirection = FlexDirection.Row;
+        actionContainer.style.alignItems = Align.Center;
+        actionContainer.style.minWidth = 150;
+
+        var sellPrice = currentShop.GetSellPrice(item);
+        var sellPriceGold = sellPrice / 100;
+        var sellPriceSilver = (sellPrice % 100) / 10;
+        var sellPriceCopper = sellPrice % 10;
+
+        var priceLabel = new Label($"Sell: {sellPriceGold}g {sellPriceSilver}s {sellPriceCopper}c");
+        priceLabel.AddToClassList("item-price");
+        priceLabel.style.fontSize = 12;
+        priceLabel.style.color = new Color(0.0f, 0.5f, 0.0f, 1f);
+        priceLabel.style.marginRight = 10;
+        priceLabel.style.minWidth = 80;
+
+        var sellButton = new Button(() => SellItem(item))
+        {
+            text = "Sell"
+        };
+        sellButton.AddToClassList("sell-button");
+        sellButton.style.width = 60;
+        sellButton.style.height = 25;
+        sellButton.style.fontSize = 12;
+
+        // Check if shop accepts this item
+        if (!currentShop.CanBuyItem(item))
+        {
+            sellButton.SetEnabled(false);
+            priceLabel.text = "Not accepted";
+            priceLabel.style.color = new Color(0.8f, 0.2f, 0.2f, 1f);
+        }
+
+        actionContainer.Add(priceLabel);
+        actionContainer.Add(sellButton);
+
+        itemElement.Add(infoContainer);
+        itemElement.Add(actionContainer);
+
+        itemList.Add(itemElement);
+    }
+
+    private void BuyItem(ShopInventoryItem shopItem)
+    {
+        if (selectedCustomer == null || shopItem == null) return;
+
+        // Use ShopInventoryItem's Purchase method which handles money transaction
+        if (shopItem.CanAfford(selectedCustomer))
+        {
+            shopItem.Purchase(selectedCustomer);
+
+            // Add item to player's inventory (this needs proper implementation)
+            // For now, we'll add to the appropriate string list
+            AddItemToPlayerInventory(shopItem.item);
+
+            // Refresh UI
+            RefreshItemList();
+            UpdateMoneyDisplay();
+
+            Debug.Log($"Bought {shopItem.item.itemName}");
+        }
+        else
+        {
+            Debug.Log("Not enough money!");
+        }
+    }
+
+    private void AddItemToPlayerInventory(Item item)
+    {
+        if (selectedCustomer == null || item == null) return;
+
+        // Add item name to appropriate list based on item type
+        switch (item.itemType)
+        {
+            case ItemType.Weapon:
+                if (selectedCustomer.weapons == null)
+                    selectedCustomer.weapons = new List<string>();
+                selectedCustomer.weapons.Add(item.itemName);
+                break;
+            case ItemType.Armor:
+                if (selectedCustomer.armor == null)
+                    selectedCustomer.armor = new List<string>();
+                selectedCustomer.armor.Add(item.itemName);
+                break;
+            case ItemType.Consumable:
+            case ItemType.Miscellaneous:
+            case ItemType.Tool:
+            case ItemType.Accessory:
+                if (selectedCustomer.miscItems == null)
+                    selectedCustomer.miscItems = new List<string>();
+                selectedCustomer.miscItems.Add(item.itemName);
+                break;
+        }
+    }
+
+    private void SellItem(Item item)
+    {
+        if (selectedCustomer == null || item == null) return;
+
+        var sellPrice = currentShop.GetSellPrice(item);
+
+        if (sellPrice > 0)
+        {
+            // Add money to player using the shop's method
+            currentShop.SellItemToShop(item, selectedCustomer);
+
+            // Remove item from player inventory
+            RemoveItemFromPlayerInventory(item);
+
+            // Refresh UI
+            RefreshItemList();
+            UpdateMoneyDisplay();
+
+            Debug.Log($"Sold {item.itemName} for {sellPrice / 100}g");
+        }
+        else
+        {
+            Debug.Log("Shop doesn't accept this item!");
+        }
+    }
+
+    private void RemoveItemFromPlayerInventory(Item item)
+    {
+        if (selectedCustomer == null || item == null) return;
+
+        // Remove item name from appropriate list
+        switch (item.itemType)
+        {
+            case ItemType.Weapon:
+                selectedCustomer.weapons?.Remove(item.itemName);
+                break;
+            case ItemType.Armor:
+                selectedCustomer.armor?.Remove(item.itemName);
+                break;
+            case ItemType.Consumable:
+            case ItemType.Miscellaneous:
+            case ItemType.Tool:
+            case ItemType.Accessory:
+                selectedCustomer.miscItems?.Remove(item.itemName);
+                break;
+        }
+    }
+
+    private void SwitchToBuyMode()
+    {
+        isSellMode = false;
+
+        if (buyTab != null)
+        {
+            buyTab.AddToClassList("active-tab");
+        }
+
+        if (sellTab != null)
+        {
+            sellTab.RemoveFromClassList("active-tab");
+        }
+
+        RefreshItemList();
+    }
+
+    private void SwitchToSellMode()
+    {
+        isSellMode = true;
+
+        if (sellTab != null)
+        {
+            sellTab.AddToClassList("active-tab");
+        }
+
+        if (buyTab != null)
+        {
+            buyTab.RemoveFromClassList("active-tab");
+        }
+
+        RefreshItemList();
+    }
+}

+ 84 - 0
Assets/Scripts/Town/TownShopUIDebugger.cs

@@ -0,0 +1,84 @@
+using UnityEngine;
+using UnityEngine.UIElements;
+
+[System.Serializable]
+public class TownShopUIDebugger : MonoBehaviour
+{
+    [ContextMenu("Debug Shop UI State")]
+    public void DebugShopUIState()
+    {
+        var shopUIs = FindObjectsByType<TownShopUI>(FindObjectsSortMode.None);
+        Debug.Log($"Found {shopUIs.Length} TownShopUI instances");
+
+        foreach (var shopUI in shopUIs)
+        {
+            Debug.Log($"=== TownShopUI: {shopUI.gameObject.name} ===");
+
+            var uiDoc = shopUI.GetComponent<UIDocument>();
+            if (uiDoc != null)
+            {
+                Debug.Log($"UIDocument found - enabled: {uiDoc.enabled}");
+                Debug.Log($"PanelSettings: {uiDoc.panelSettings != null}");
+                Debug.Log($"SortingOrder: {uiDoc.sortingOrder}");
+                Debug.Log($"VisualTreeAsset: {uiDoc.visualTreeAsset != null}");
+
+                if (uiDoc.rootVisualElement != null)
+                {
+                    var root = uiDoc.rootVisualElement;
+                    Debug.Log($"Root element - visible: {root.visible}, display: {root.style.display.value}, position: {root.style.position.value}");
+                    Debug.Log($"Root worldBound: {root.worldBound}");
+
+                    var shopContainer = root.Q<VisualElement>("shop-container");
+                    if (shopContainer != null)
+                    {
+                        Debug.Log($"Shop container - visible: {shopContainer.visible}, display: {shopContainer.style.display.value}");
+                        Debug.Log($"Shop container worldBound: {shopContainer.worldBound}");
+                    }
+                    else
+                    {
+                        Debug.LogError("shop-container element not found!");
+                    }
+                }
+                else
+                {
+                    Debug.LogError("Root visual element is null!");
+                }
+            }
+            else
+            {
+                Debug.LogError("No UIDocument component found!");
+            }
+        }
+
+        // Check all UIDocuments in scene
+        var allUIDocuments = FindObjectsByType<UIDocument>(FindObjectsSortMode.None);
+        Debug.Log($"\n=== All UIDocuments in scene ({allUIDocuments.Length}) ===");
+        foreach (var doc in allUIDocuments)
+        {
+            var panelSort = doc.panelSettings?.sortingOrder ?? -999;
+            Debug.Log($"UIDocument '{doc.gameObject.name}' - sortingOrder: {doc.sortingOrder}, PanelSettings sortingOrder: {panelSort}");
+        }
+    }
+
+    [ContextMenu("Force Open Test Shop")]
+    public void ForceOpenTestShop()
+    {
+        // Create a test shop
+        var testShop = new TownShop
+        {
+            buildingName = "Test Shop",
+            shopkeeperName = "Test Keeper",
+            shopType = ShopType.General
+        };
+
+        var townManager = FindFirstObjectByType<TownManager>();
+        if (townManager != null)
+        {
+            townManager.OnBuildingClicked(testShop);
+        }
+        else
+        {
+            Debug.LogError("TownManager not found!");
+        }
+    }
+}

+ 0 - 0
Assets/Scripts/Town/TownShopUI_Clean.cs


+ 0 - 0
Assets/Scripts/Town/TownShopUI_Fixed.cs


+ 204 - 0
Assets/Scripts/UI/SettlementInteractionUI.cs

@@ -0,0 +1,204 @@
+using UnityEngine;
+using UnityEngine.UIElements;
+
+/// <summary>
+/// Simple UI controller for settlement interaction prompts
+/// Displays when near a settlement and shows interaction instructions
+/// </summary>
+public class SettlementInteractionUI : MonoBehaviour
+{
+    [Header("UI References")]
+    [Tooltip("UI Document for settlement interaction prompt")]
+    public UIDocument uiDocument;
+
+    [Header("UI Element Names")]
+    [Tooltip("Name of the interaction prompt container in UXML")]
+    public string promptContainerName = "SettlementPrompt";
+
+    [Tooltip("Name of the settlement name label in UXML")]
+    public string settlementNameLabelName = "SettlementName";
+
+    [Tooltip("Name of the interaction instruction label in UXML")]
+    public string instructionLabelName = "InteractionInstruction";
+
+    // UI Elements
+    private VisualElement promptContainer;
+    private Label settlementNameLabel;
+    private Label instructionLabel;
+
+    // References
+    private SettlementInteractionManager interactionManager;
+
+    void Start()
+    {
+        InitializeUI();
+        SetupEventListeners();
+    }
+
+    /// <summary>
+    /// Initialize UI elements
+    /// </summary>
+    private void InitializeUI()
+    {
+        if (uiDocument == null)
+        {
+            uiDocument = GetComponent<UIDocument>();
+        }
+
+        if (uiDocument == null)
+        {
+            Debug.LogError("SettlementInteractionUI: No UIDocument found!");
+            return;
+        }
+
+        var root = uiDocument.rootVisualElement;
+
+        // Find UI elements
+        promptContainer = root.Q<VisualElement>(promptContainerName);
+        settlementNameLabel = root.Q<Label>(settlementNameLabelName);
+        instructionLabel = root.Q<Label>(instructionLabelName);
+
+        // Initially hide the prompt
+        if (promptContainer != null)
+        {
+            promptContainer.style.display = DisplayStyle.None;
+        }
+
+        Debug.Log("SettlementInteractionUI initialized");
+    }
+
+    /// <summary>
+    /// Setup event listeners for settlement interaction
+    /// </summary>
+    private void SetupEventListeners()
+    {
+        interactionManager = FindFirstObjectByType<SettlementInteractionManager>();
+
+        if (interactionManager != null)
+        {
+            interactionManager.OnSettlementDetected += ShowSettlementPrompt;
+            interactionManager.OnSettlementLeft += HideSettlementPrompt;
+            interactionManager.OnSettlementEntered += OnSettlementEntered;
+
+            Debug.Log("SettlementInteractionUI connected to SettlementInteractionManager");
+        }
+        else
+        {
+            Debug.LogWarning("SettlementInteractionUI: SettlementInteractionManager not found!");
+        }
+    }
+
+    /// <summary>
+    /// Show settlement interaction prompt
+    /// </summary>
+    private void ShowSettlementPrompt(Settlement settlement)
+    {
+        if (promptContainer == null) return;
+
+        // Update settlement name
+        if (settlementNameLabel != null)
+        {
+            settlementNameLabel.text = settlement.name;
+        }
+
+        // Update interaction instruction
+        if (instructionLabel != null)
+        {
+            string settlementType = settlement.Type == SettlementType.Town ? "Town" : "Village";
+            string keyName = interactionManager?.enterSettlementKey.ToString() ?? "E";
+            instructionLabel.text = $"Press {keyName} to enter {settlementType}";
+        }
+
+        // Show the prompt
+        promptContainer.style.display = DisplayStyle.Flex;
+
+        Debug.Log($"Showing prompt for: {settlement.name}");
+    }
+
+    /// <summary>
+    /// Hide settlement interaction prompt
+    /// </summary>
+    private void HideSettlementPrompt()
+    {
+        if (promptContainer != null)
+        {
+            promptContainer.style.display = DisplayStyle.None;
+        }
+
+        Debug.Log("Hiding settlement prompt");
+    }
+
+    /// <summary>
+    /// Handle settlement entry (cleanup if needed)
+    /// </summary>
+    private void OnSettlementEntered(Settlement settlement)
+    {
+        Debug.Log($"Entering settlement: {settlement.name}");
+        // UI will be destroyed when scene changes, no cleanup needed
+    }
+
+    void OnDestroy()
+    {
+        // Cleanup event listeners
+        if (interactionManager != null)
+        {
+            interactionManager.OnSettlementDetected -= ShowSettlementPrompt;
+            interactionManager.OnSettlementLeft -= HideSettlementPrompt;
+            interactionManager.OnSettlementEntered -= OnSettlementEntered;
+        }
+    }
+
+    /// <summary>
+    /// Force UI to show (for testing or manual control)
+    /// </summary>
+    public void ForceShowUI()
+    {
+        if (promptContainer != null)
+        {
+            promptContainer.style.display = DisplayStyle.Flex;
+
+            // Update with current nearby settlement if available
+            if (interactionManager != null)
+            {
+                var currentSettlement = interactionManager.GetCurrentNearbySettlement();
+                if (currentSettlement != null)
+                {
+                    ShowSettlementPrompt(currentSettlement);
+                    return;
+                }
+            }
+
+            // Fallback: show with generic text
+            if (settlementNameLabel != null)
+            {
+                settlementNameLabel.text = "Nearby Settlement";
+            }
+            if (instructionLabel != null)
+            {
+                instructionLabel.text = "Press E to enter";
+            }
+
+            Debug.Log("[SettlementUI] Force showing UI");
+        }
+    }
+
+    /// <summary>
+    /// Force UI to hide (for testing or manual control)
+    /// </summary>
+    public void ForceHideUI()
+    {
+        if (promptContainer != null)
+        {
+            promptContainer.style.display = DisplayStyle.None;
+            Debug.Log("[SettlementUI] Force hiding UI");
+        }
+    }
+
+    /// <summary>
+    /// Check if UI is currently visible
+    /// </summary>
+    public bool IsUIVisible()
+    {
+        return promptContainer != null && promptContainer.style.display == DisplayStyle.Flex;
+    }
+}

+ 88 - 0
Assets/Scripts/UI/SettlementUIBridge.cs

@@ -0,0 +1,88 @@
+using UnityEngine;
+
+/// <summary>
+/// Bridge component that connects SettlementInteractionManager's GameObject control
+/// with SettlementInteractionUI's UI Toolkit system
+/// </summary>
+public class SettlementUIBridge : MonoBehaviour
+{
+    [Header("UI Bridge")]
+    [Tooltip("The SettlementInteractionUI component to control")]
+    public SettlementInteractionUI settlementUI;
+
+    [Tooltip("Should this GameObject's active state control the UI visibility?")]
+    public bool controlUIVisibility = true;
+
+    private bool lastActiveState;
+
+    void Start()
+    {
+        // Find SettlementInteractionUI if not assigned
+        if (settlementUI == null)
+        {
+            // First try to get from same GameObject
+            settlementUI = GetComponent<SettlementInteractionUI>();
+        }
+
+        if (settlementUI == null)
+        {
+            // Then try to find in scene
+            settlementUI = FindFirstObjectByType<SettlementInteractionUI>();
+        }
+
+        if (settlementUI != null)
+        {
+            Debug.Log("[UIBridge] Connected to SettlementInteractionUI");
+
+            // Force initial state
+            lastActiveState = gameObject.activeSelf;
+            UpdateUIVisibility();
+        }
+        else
+        {
+            Debug.LogError("[UIBridge] SettlementInteractionUI not found! Make sure it's on the same GameObject.");
+        }
+    }
+    void Update()
+    {
+        if (!controlUIVisibility) return;
+
+        // Check if GameObject active state changed
+        bool currentActiveState = gameObject.activeSelf;
+        if (currentActiveState != lastActiveState)
+        {
+            lastActiveState = currentActiveState;
+            UpdateUIVisibility();
+        }
+    }
+
+    private void UpdateUIVisibility()
+    {
+        if (settlementUI == null) return;
+
+        if (gameObject.activeSelf)
+        {
+            Debug.Log("[UIBridge] GameObject activated - UI should show");
+            // Force UI to show with test data if no real settlement detected
+            settlementUI.ForceShowUI();
+        }
+        else
+        {
+            Debug.Log("[UIBridge] GameObject deactivated - UI should hide");
+            settlementUI.ForceHideUI();
+        }
+    }
+
+    void OnEnable()
+    {
+        UpdateUIVisibility();
+    }
+
+    void OnDisable()
+    {
+        if (settlementUI != null)
+        {
+            settlementUI.ForceHideUI();
+        }
+    }
+}

+ 101 - 0
Assets/UI/TownShopUI.uss

@@ -0,0 +1,101 @@
+/* Shop Item Styles */
+.shop-item {
+    flex-direction: row;
+    align-items: center;
+    justify-content: space-between;
+    padding: 10px;
+    margin-bottom: 5px;
+    background-color: rgb(250, 250, 250);
+    border-width: 1px;
+    border-color: rgb(200, 200, 200);
+    border-radius: 5px;
+}
+
+.shop-item:hover {
+    background-color: rgb(240, 240, 240);
+}
+
+.sell-item {
+    flex-direction: row;
+    align-items: center;
+    justify-content: space-between;
+    padding: 10px;
+    margin-bottom: 5px;
+    background-color: rgb(250, 245, 240);
+    border-width: 1px;
+    border-color: rgb(200, 180, 160);
+    border-radius: 5px;
+}
+
+.sell-item:hover {
+    background-color: rgb(240, 235, 230);
+}
+
+.item-name {
+    font-size: 16px;
+    color: rgb(50, 50, 50);
+    font-weight: bold;
+    flex-shrink: 0;
+    width: 200px;
+}
+
+.item-description {
+    font-size: 12px;
+    color: rgb(100, 100, 100);
+    flex-grow: 1;
+    margin-left: 10px;
+    margin-right: 10px;
+}
+
+.item-price {
+    font-size: 14px;
+    color: rgb(0, 120, 0);
+    font-weight: bold;
+    flex-shrink: 0;
+    width: 100px;
+    text-align: center;
+}
+
+.buy-button {
+    background-color: rgb(50, 150, 50);
+    color: rgb(255, 255, 255);
+    border-width: 0;
+    border-radius: 3px;
+    padding: 5px 15px;
+    font-weight: bold;
+}
+
+.buy-button:hover {
+    background-color: rgb(40, 130, 40);
+}
+
+.sell-button {
+    background-color: rgb(150, 100, 50);
+    color: rgb(255, 255, 255);
+    border-width: 0;
+    border-radius: 3px;
+    padding: 5px 15px;
+    font-weight: bold;
+}
+
+.sell-button:hover {
+    background-color: rgb(130, 80, 30);
+}
+
+.unaffordable {
+    color: rgb(150, 50, 50) !important;
+}
+
+.not-accepted {
+    color: rgb(150, 50, 50) !important;
+}
+
+.active-tab {
+    background-color: rgb(200, 180, 140) !important;
+    color: rgb(50, 50, 50) !important;
+}
+
+/* Medieval styling for the shop window */
+#shop-window {
+    background-image: url('project://database/Assets/UI/medieval-background.png');
+}

+ 38 - 0
Assets/UI/TownShopUI.uxml

@@ -0,0 +1,38 @@
+<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
+    <ui:VisualElement name="shop-container" style="position: absolute; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.8); justify-content: center; align-items: center; display: none;">
+        <ui:VisualElement name="shop-window" style="width: 800px; height: 600px; background-color: rgb(240, 220, 180); border-left-color: rgb(139, 69, 19); border-right-color: rgb(139, 69, 19); border-top-color: rgb(139, 69, 19); border-bottom-color: rgb(139, 69, 19); border-left-width: 3px; border-right-width: 3px; border-top-width: 3px; border-bottom-width: 3px; border-top-left-radius: 10px; border-bottom-left-radius: 10px; border-top-right-radius: 10px; border-bottom-right-radius: 10px; padding-left: 20px; padding-right: 20px; padding-top: 20px; padding-bottom: 20px;">
+            
+            <!-- Shop Header -->
+            <ui:VisualElement name="shop-header" style="flex-direction: row; justify-content: space-between; align-items: center; margin-bottom: 15px; height: 40px;">
+                <ui:VisualElement style="flex-direction: column;">
+                    <ui:Label name="shop-name" text="General Store" style="font-size: 24px; color: rgb(139, 69, 19); -unity-font-style: bold;" />
+                    <ui:Label name="shopkeeper-name" text="Shopkeeper: Merchant" style="font-size: 14px; color: rgb(80, 40, 10); font-style: italic;" />
+                </ui:VisualElement>
+                <ui:Button name="close-button" text="✕" style="width: 30px; height: 30px; background-color: rgb(200, 50, 50); color: rgb(255, 255, 255); border-width: 0; border-top-left-radius: 15px; border-bottom-left-radius: 15px; border-top-right-radius: 15px; border-bottom-right-radius: 15px; font-size: 16px; -unity-font-style: bold;" />
+            </ui:VisualElement>
+
+            <!-- Customer Panel -->
+            <ui:VisualElement name="customer-panel" style="flex-direction: row; justify-content: space-between; align-items: center; margin-bottom: 15px; background-color: rgb(220, 200, 160); padding-left: 10px; padding-right: 10px; padding-top: 10px; padding-bottom: 10px; border-top-left-radius: 5px; border-bottom-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px;">
+                <ui:DropdownField name="customer-dropdown" label="Customer:" style="width: 200px;" />
+                <ui:Label name="money-label" text="Money: 100g 50s 25c" style="color: rgb(0, 120, 0); -unity-font-style: bold;" />
+            </ui:VisualElement>
+
+            <!-- Tab Container -->
+            <ui:VisualElement name="tab-container" style="flex-direction: row; margin-bottom: 15px; height: 35px;">
+                <ui:Button name="buy-tab" text="Buy" class="active-tab" style="flex-grow: 1; margin-right: 5px; background-color: rgb(200, 180, 140); border-width: 1px; border-color: rgb(139, 69, 19); border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-left-radius: 0; border-bottom-right-radius: 0;" />
+                <ui:Button name="sell-tab" text="Sell" style="flex-grow: 1; margin-left: 5px; background-color: rgb(180, 160, 120); border-width: 1px; border-color: rgb(139, 69, 19); border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-left-radius: 0; border-bottom-right-radius: 0;" />
+            </ui:VisualElement>
+
+            <!-- Filters -->
+            <ui:VisualElement name="filters" style="flex-direction: row; margin-bottom: 15px; align-items: center;">
+                <ui:TextField name="search-field" label="Search:" placeholder-text="Enter item name..." style="flex-grow: 1; margin-right: 10px;" />
+                <ui:DropdownField name="category-filter" label="Category:" style="width: 150px;" />
+            </ui:VisualElement>
+
+            <!-- Item List -->
+            <ui:ScrollView name="item-list" style="flex-grow: 1; min-height: 200px; background-color: rgb(255, 255, 255); border-width: 1px; border-color: rgb(139, 69, 19); border-top-left-radius: 5px; border-bottom-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; padding-left: 10px; padding-right: 10px; padding-top: 10px; padding-bottom: 10px;">
+                <ui:Label text="Items will appear here..." style="color: rgb(150, 150, 150); font-style: italic; -unity-text-align: middle-center; margin-top: 50px;" />
+            </ui:ScrollView>
+        </ui:VisualElement>
+    </ui:VisualElement>
+</ui:UXML>

+ 272 - 0
Assets/UI/TownUI.uss

@@ -0,0 +1,272 @@
+/* Medieval Town UI Styles */
+
+/* Main Town Container */
+.town-container {
+    width: 100%;
+    height: 100%;
+    background-color: rgb(101, 67, 33); /* Medieval brown background */
+}
+
+/* Header Styles */
+.town-header {
+    background-color: rgb(139, 69, 19);
+    padding: 10px;
+    justify-content: space-between;
+    flex-direction: row;
+    border-bottom-width: 3px;
+    border-bottom-color: rgb(101, 67, 33);
+    min-height: 60px;
+}
+
+.town-title {
+    font-size: 24px;
+    color: rgb(255, 215, 0);
+    -unity-font-style: bold;
+    -unity-text-align: middle-left;
+}
+
+.header-controls {
+    flex-direction: row;
+    align-items: center;
+}
+
+.header-button {
+    background-color: rgb(160, 82, 45);
+    color: rgb(255, 255, 255);
+    border-width: 2px;
+    border-color: rgb(101, 67, 33);
+    padding: 8px 16px;
+    margin-left: 10px;
+    border-radius: 5px;
+    font-size: 14px;
+    -unity-font-style: bold;
+}
+
+.header-button:hover {
+    background-color: rgb(205, 133, 63);
+    scale: 1.05;
+}
+
+/* Medieval Town Grid Layout */
+.town-grid {
+    flex-grow: 1;
+    padding: 20px;
+    align-items: center;
+    justify-content: center;
+}
+
+/* Town Walls */
+.town-wall-horizontal {
+    height: 20px;
+    background-color: rgb(75, 75, 75);
+    width: 100%;
+    border-top-width: 2px;
+    border-bottom-width: 2px;
+    border-color: rgb(55, 55, 55);
+    margin: 5px 0;
+}
+
+/* Districts */
+.town-district {
+    flex-direction: row;
+    justify-content: space-around;
+    align-items: flex-end;
+    width: 100%;
+    margin: 10px 0;
+    min-height: 120px;
+}
+
+/* Streets */
+.main-street {
+    height: 30px;
+    background-color: rgb(160, 160, 160);
+    width: 80%;
+    align-self: center;
+    margin: 5px 0;
+    border-radius: 3px;
+}
+
+.side-street {
+    height: 20px;
+    background-color: rgb(140, 140, 140);
+    width: 60%;
+    align-self: center;
+    margin: 5px 0;
+    border-radius: 2px;
+}
+
+/* Base Building Styles */
+.town-building {
+    width: 120px;
+    height: 100px;
+    border-width: 3px;
+    border-color: rgb(101, 67, 33);
+    margin: 5px;
+    padding: 5px;
+    justify-content: space-between;
+    align-items: center;
+    border-radius: 8px;
+    position: relative;
+}
+
+.building-label {
+    font-size: 12px;
+    color: rgb(255, 255, 255);
+    -unity-font-style: bold;
+    -unity-text-align: middle-center;
+}
+
+/* Interactive Building Effects */
+.interactable-building {
+    border-color: rgb(255, 215, 0);
+    border-width: 4px;
+}
+
+.interactable-building:hover {
+    scale: 1.1;
+    border-color: rgb(255, 255, 255);
+}
+
+/* Shop Building Colors */
+.weapon-shop {
+    background-color: rgb(178, 34, 34);
+}
+
+.armor-shop {
+    background-color: rgb(70, 130, 180);
+}
+
+.potion-shop {
+    background-color: rgb(138, 43, 226);
+}
+
+.general-shop {
+    background-color: rgb(255, 140, 0);
+}
+
+/* Special Buildings */
+.castle {
+    background-color: rgb(112, 128, 144);
+    width: 180px;
+    height: 140px;
+}
+
+.noble-house {
+    background-color: rgb(188, 143, 143);
+    width: 140px;
+    height: 110px;
+}
+
+.guild {
+    background-color: rgb(184, 134, 11);
+}
+
+.inn {
+    background-color: rgb(160, 82, 45);
+}
+
+.harbor {
+    background-color: rgb(72, 61, 139);
+}
+
+.town-house {
+    background-color: rgb(205, 133, 63);
+    width: 80px;
+    height: 80px;
+}
+
+/* Town Square */
+.town-square {
+    background-color: rgb(143, 188, 143);
+    width: 150px;
+    height: 120px;
+    border-radius: 50%;
+    justify-content: center;
+    align-items: center;
+}
+
+.fountain {
+    width: 40px;
+    height: 40px;
+    background-color: rgb(135, 206, 235);
+    border-radius: 50%;
+    border-width: 2px;
+    border-color: rgb(169, 169, 169);
+}
+
+/* Shop Banners */
+.shop-banner {
+    background-color: rgb(220, 20, 60);
+    width: 110px;
+    height: 20px;
+    justify-content: center;
+    align-items: center;
+    border-radius: 3px;
+    position: absolute;
+    top: -15px;
+    left: 5px;
+}
+
+.interaction-banner {
+    background-color: rgb(255, 215, 0);
+    width: 110px;
+    height: 20px;
+    justify-content: center;
+    align-items: center;
+    border-radius: 3px;
+    position: absolute;
+    top: -15px;
+    left: 5px;
+}
+
+.banner-text {
+    font-size: 10px;
+    color: rgb(255, 255, 255);
+    -unity-font-style: bold;
+    -unity-text-align: middle-center;
+}
+
+/* Bottom Panel */
+.bottom-panel {
+    background-color: rgb(139, 69, 19);
+    padding: 15px;
+    flex-direction: row;
+    justify-content: space-between;
+    align-items: center;
+    border-top-width: 3px;
+    border-top-color: rgb(101, 67, 33);
+    min-height: 50px;
+}
+
+.interaction-hint {
+    font-size: 14px;
+    color: rgb(255, 215, 0);
+    -unity-font-style: italic;
+}
+
+.money-display {
+    flex-direction: row;
+    align-items: center;
+}
+
+.money-label {
+    font-size: 14px;
+    color: rgb(255, 255, 255);
+    margin-right: 10px;
+    -unity-font-style: bold;
+}
+
+.money-amount {
+    font-size: 16px;
+    color: rgb(255, 215, 0);
+    -unity-font-style: bold;
+    background-color: rgba(0, 0, 0, 0.3);
+    padding: 5px 10px;
+    border-radius: 5px;
+}
+
+/* Hover Effects for All Buildings */
+.town-building:hover .building-label {
+    color: rgb(255, 215, 0);
+    font-size: 13px;
+}

+ 129 - 0
Assets/UI/TownUI.uxml

@@ -0,0 +1,129 @@
+<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
+    <Style src="project://database/Assets/UI/TownUI.uss?fileID=7433441132597879392&amp;guid=f1e9910cf9c584544b8fe7ed144173e5&amp;type=3#TownUI" />
+    
+    <!-- Main Town Container -->
+    <ui:VisualElement name="TownContainer" style="width: 100%; height: 100%; background-color: rgb(101, 67, 33);">
+        
+        <!-- Header Section -->
+        <ui:VisualElement name="TownHeader" class="town-header">
+            <ui:Label name="TownNameLabel" text="Haven Village" class="town-title" />
+            <ui:VisualElement name="HeaderControls" class="header-controls">
+                <ui:Button name="MapButton" text="Return to Map" class="header-button" />
+                <ui:Button name="InventoryButton" text="Team Inventory" class="header-button" />
+            </ui:VisualElement>
+        </ui:VisualElement>
+        
+        <!-- Medieval Town Layout -->
+        <ui:VisualElement name="TownGrid" class="town-grid">
+            
+            <!-- Outer Town Wall (Top) -->
+            <ui:VisualElement name="TownWallTop" class="town-wall-horizontal" />
+            
+            <!-- Upper District -->
+            <ui:VisualElement name="UpperDistrict" class="town-district">
+                <!-- Castle/Manor Quarter -->
+                <ui:VisualElement name="CastleQuarter" class="town-building castle">
+                    <ui:Label text="🏰 Lord's Manor" class="building-label" />
+                </ui:VisualElement>
+                
+                <!-- Noble Houses -->
+                <ui:VisualElement name="NobleHouse1" class="town-building noble-house">
+                    <ui:Label text="🏛️ Noble House" class="building-label" />
+                </ui:VisualElement>
+                
+                <!-- Adventurer's Guild -->
+                <ui:VisualElement name="AdventurersGuild" class="town-building town-special guild interactable-building">
+                    <ui:Label text="⚔️ Adventurer's Guild" class="building-label" />
+                    <ui:VisualElement class="interaction-banner">
+                        <ui:Label text="Click to Enter" class="banner-text" />
+                    </ui:VisualElement>
+                </ui:VisualElement>
+            </ui:VisualElement>
+            
+            <!-- Main Street (Horizontal) -->
+            <ui:VisualElement name="MainStreet" class="main-street" />
+            
+            <!-- Market District -->
+            <ui:VisualElement name="MarketDistrict" class="town-district">
+                <!-- Weapon Shop -->
+                <ui:VisualElement name="WeaponShop" class="town-building town-shop weapon-shop interactable-building">
+                    <ui:Label text="⚔️ The Forge" name="building-name" class="building-label" />
+                    <ui:VisualElement class="shop-banner">
+                        <ui:Label text="WEAPONS" class="banner-text" />
+                    </ui:VisualElement>
+                </ui:VisualElement>
+                
+                <!-- Market Square -->
+                <ui:VisualElement name="TownSquare" class="town-square">
+                    <ui:Label text="🏛️ Market Square" class="building-label" />
+                    <ui:VisualElement name="Fountain" class="fountain" />
+                </ui:VisualElement>
+                
+                <!-- Armor Shop -->
+                <ui:VisualElement name="ArmorShop" class="town-building town-shop armor-shop interactable-building">
+                    <ui:Label text="🛡️ Ironclad Armory" name="building-name" class="building-label" />
+                    <ui:VisualElement class="shop-banner">
+                        <ui:Label text="ARMOR" class="banner-text" />
+                    </ui:VisualElement>
+                </ui:VisualElement>
+                
+                <!-- Potion Shop -->
+                <ui:VisualElement name="PotionShop" class="town-building town-shop potion-shop interactable-building">
+                    <ui:Label text="🧪 The Bubbling Cauldron" name="building-name" class="building-label" />
+                    <ui:VisualElement class="shop-banner">
+                        <ui:Label text="POTIONS" class="banner-text" />
+                    </ui:VisualElement>
+                </ui:VisualElement>
+            </ui:VisualElement>
+            
+            <!-- Side Street -->
+            <ui:VisualElement name="SideStreet" class="side-street" />
+            
+            <!-- Lower District -->
+            <ui:VisualElement name="LowerDistrict" class="town-district">
+                <!-- General Store -->
+                <ui:VisualElement name="GeneralStore" class="town-building town-shop general-shop interactable-building">
+                    <ui:Label text="🏪 Pete's General Goods" name="building-name" class="building-label" />
+                    <ui:VisualElement class="shop-banner">
+                        <ui:Label text="GENERAL STORE" class="banner-text" />
+                    </ui:VisualElement>
+                </ui:VisualElement>
+                
+                <!-- Inn -->
+                <ui:VisualElement name="Inn" class="town-building town-special inn interactable-building">
+                    <ui:Label text="🍺 The Wanderer's Rest" class="building-label" />
+                    <ui:VisualElement class="interaction-banner">
+                        <ui:Label text="Click to Enter" class="banner-text" />
+                    </ui:VisualElement>
+                </ui:VisualElement>
+                
+                <!-- Harbor (if enabled) -->
+                <ui:VisualElement name="Harbor" class="town-building town-special harbor interactable-building">
+                    <ui:Label text="⚓ Harbor" class="building-label" />
+                    <ui:VisualElement class="interaction-banner">
+                        <ui:Label text="Click to Enter" class="banner-text" />
+                    </ui:VisualElement>
+                </ui:VisualElement>
+                
+                <!-- Common Houses -->
+                <ui:VisualElement name="House1" class="town-building town-house">
+                    <ui:Label text="🏠 House" class="building-label" />
+                </ui:VisualElement>
+            </ui:VisualElement>
+            
+            <!-- Outer Town Wall (Bottom) -->
+            <ui:VisualElement name="TownWallBottom" class="town-wall-horizontal" />
+            
+        </ui:VisualElement>
+        
+        <!-- Bottom UI Panel -->
+        <ui:VisualElement name="BottomPanel" class="bottom-panel">
+            <ui:Label name="InteractionHint" text="Click on buildings with banners to interact with them" class="interaction-hint" />
+            <ui:VisualElement name="MoneyDisplay" class="money-display">
+                <ui:Label text="Party Funds:" class="money-label" />
+                <ui:Label name="MoneyAmount" text="100g 50s 25c" class="money-amount" />
+            </ui:VisualElement>
+        </ui:VisualElement>
+        
+    </ui:VisualElement>
+</ui:UXML>

+ 272 - 0
Assets/UI/TownUI_New.uss

@@ -0,0 +1,272 @@
+/* Medieval Town UI Styles */
+
+/* Main Town Container */
+.town-container {
+    width: 100%;
+    height: 100%;
+    background-color: rgb(101, 67, 33); /* Medieval brown background */
+}
+
+/* Header Styles */
+.town-header {
+    background-color: rgb(139, 69, 19);
+    padding: 10px;
+    justify-content: space-between;
+    flex-direction: row;
+    border-bottom-width: 3px;
+    border-bottom-color: rgb(101, 67, 33);
+    min-height: 60px;
+}
+
+.town-title {
+    font-size: 24px;
+    color: rgb(255, 215, 0);
+    -unity-font-style: bold;
+    -unity-text-align: middle-left;
+}
+
+.header-controls {
+    flex-direction: row;
+    align-items: center;
+}
+
+.header-button {
+    background-color: rgb(160, 82, 45);
+    color: rgb(255, 255, 255);
+    border-width: 2px;
+    border-color: rgb(101, 67, 33);
+    padding: 8px 16px;
+    margin-left: 10px;
+    border-radius: 5px;
+    font-size: 14px;
+    -unity-font-style: bold;
+}
+
+.header-button:hover {
+    background-color: rgb(205, 133, 63);
+    scale: 1.05;
+}
+
+/* Medieval Town Grid Layout */
+.town-grid {
+    flex-grow: 1;
+    padding: 20px;
+    align-items: center;
+    justify-content: center;
+}
+
+/* Town Walls */
+.town-wall-horizontal {
+    height: 20px;
+    background-color: rgb(75, 75, 75);
+    width: 100%;
+    border-top-width: 2px;
+    border-bottom-width: 2px;
+    border-color: rgb(55, 55, 55);
+    margin: 5px 0;
+}
+
+/* Districts */
+.town-district {
+    flex-direction: row;
+    justify-content: space-around;
+    align-items: flex-end;
+    width: 100%;
+    margin: 10px 0;
+    min-height: 120px;
+}
+
+/* Streets */
+.main-street {
+    height: 30px;
+    background-color: rgb(160, 160, 160);
+    width: 80%;
+    align-self: center;
+    margin: 5px 0;
+    border-radius: 3px;
+}
+
+.side-street {
+    height: 20px;
+    background-color: rgb(140, 140, 140);
+    width: 60%;
+    align-self: center;
+    margin: 5px 0;
+    border-radius: 2px;
+}
+
+/* Base Building Styles */
+.town-building {
+    width: 120px;
+    height: 100px;
+    border-width: 3px;
+    border-color: rgb(101, 67, 33);
+    margin: 5px;
+    padding: 5px;
+    justify-content: space-between;
+    align-items: center;
+    border-radius: 8px;
+    position: relative;
+}
+
+.building-label {
+    font-size: 12px;
+    color: rgb(255, 255, 255);
+    -unity-font-style: bold;
+    -unity-text-align: middle-center;
+}
+
+/* Interactive Building Effects */
+.interactable-building {
+    border-color: rgb(255, 215, 0);
+    border-width: 4px;
+}
+
+.interactable-building:hover {
+    scale: 1.1;
+    border-color: rgb(255, 255, 255);
+}
+
+/* Shop Building Colors */
+.weapon-shop {
+    background-color: rgb(178, 34, 34);
+}
+
+.armor-shop {
+    background-color: rgb(70, 130, 180);
+}
+
+.potion-shop {
+    background-color: rgb(138, 43, 226);
+}
+
+.general-shop {
+    background-color: rgb(255, 140, 0);
+}
+
+/* Special Buildings */
+.castle {
+    background-color: rgb(112, 128, 144);
+    width: 180px;
+    height: 140px;
+}
+
+.noble-house {
+    background-color: rgb(188, 143, 143);
+    width: 140px;
+    height: 110px;
+}
+
+.guild {
+    background-color: rgb(184, 134, 11);
+}
+
+.inn {
+    background-color: rgb(160, 82, 45);
+}
+
+.harbor {
+    background-color: rgb(72, 61, 139);
+}
+
+.town-house {
+    background-color: rgb(205, 133, 63);
+    width: 80px;
+    height: 80px;
+}
+
+/* Town Square */
+.town-square {
+    background-color: rgb(143, 188, 143);
+    width: 150px;
+    height: 120px;
+    border-radius: 50%;
+    justify-content: center;
+    align-items: center;
+}
+
+.fountain {
+    width: 40px;
+    height: 40px;
+    background-color: rgb(135, 206, 235);
+    border-radius: 50%;
+    border-width: 2px;
+    border-color: rgb(169, 169, 169);
+}
+
+/* Shop Banners */
+.shop-banner {
+    background-color: rgb(220, 20, 60);
+    width: 110px;
+    height: 20px;
+    justify-content: center;
+    align-items: center;
+    border-radius: 3px;
+    position: absolute;
+    top: -15px;
+    left: 5px;
+}
+
+.interaction-banner {
+    background-color: rgb(255, 215, 0);
+    width: 110px;
+    height: 20px;
+    justify-content: center;
+    align-items: center;
+    border-radius: 3px;
+    position: absolute;
+    top: -15px;
+    left: 5px;
+}
+
+.banner-text {
+    font-size: 10px;
+    color: rgb(255, 255, 255);
+    -unity-font-style: bold;
+    -unity-text-align: middle-center;
+}
+
+/* Bottom Panel */
+.bottom-panel {
+    background-color: rgb(139, 69, 19);
+    padding: 15px;
+    flex-direction: row;
+    justify-content: space-between;
+    align-items: center;
+    border-top-width: 3px;
+    border-top-color: rgb(101, 67, 33);
+    min-height: 50px;
+}
+
+.interaction-hint {
+    font-size: 14px;
+    color: rgb(255, 215, 0);
+    -unity-font-style: italic;
+}
+
+.money-display {
+    flex-direction: row;
+    align-items: center;
+}
+
+.money-label {
+    font-size: 14px;
+    color: rgb(255, 255, 255);
+    margin-right: 10px;
+    -unity-font-style: bold;
+}
+
+.money-amount {
+    font-size: 16px;
+    color: rgb(255, 215, 0);
+    -unity-font-style: bold;
+    background-color: rgba(0, 0, 0, 0.3);
+    padding: 5px 10px;
+    border-radius: 5px;
+}
+
+/* Hover Effects for All Buildings */
+.town-building:hover .building-label {
+    color: rgb(255, 215, 0);
+    font-size: 13px;
+}

+ 58 - 0
DEBUG_SETTLEMENT_INTERACTION.md

@@ -0,0 +1,58 @@
+# Debug Settlement Interaction Issues
+
+## Problem
+User reports that settlement interaction UI shows correctly (settlement name and "Press E to enter Town") but pressing E doesn't trigger town scene loading.
+
+## Analysis of Code
+
+### SettlementInteractionManager Analysis
+From examining the code:
+
+1. **Input Handling**: `HandleInput()` method checks:
+   ```csharp
+   if (currentNearbySettlement != null && Input.GetKeyDown(enterSettlementKey))
+   {
+       EnterSettlement(currentNearbySettlement);
+   }
+   ```
+
+2. **Debug Logging**: Is enabled (`enableDebugLogs = true`)
+
+3. **Settlement Detection**: `CheckForSettlementInteraction()` converts world to map coordinates and finds nearby settlements
+
+4. **UI Updates**: `UpdateUI()` shows/hides `interactionPrompt` GameObject
+
+## Potential Issues
+
+### Issue 1: GameObject Not Instantiated
+The SettlementInteractionManager component might not be attached to a GameObject in MapScene2, or the GameObject might be inactive.
+
+### Issue 2: Missing TeamMarker Reference
+The `teamMarker` field might not be assigned, causing the system to not track position properly.
+
+### Issue 3: MapData Not Initialized
+The `mapData` reference might be null, causing `FindNearestSettlement()` to return null.
+
+### Issue 4: Input System Conflict
+If the project uses the new Input System, `Input.GetKeyDown()` might not work properly.
+
+### Issue 5: Settlement Detection Distance
+The `interactionDistance` might be too small, or coordinate conversion might be incorrect.
+
+### Issue 6: UI vs Logic Disconnect
+The UI is showing (via SettlementInteractionUI) but the manager's `currentNearbySettlement` might be null.
+
+## Debugging Steps Needed
+
+1. **Check GameObject Setup**: Verify SettlementInteractionManager is attached to active GameObject in MapScene2
+2. **Check References**: Verify teamMarker and mapData are assigned
+3. **Check Console**: Look for debug messages when moving TeamMarker near settlements
+4. **Test Manual Entry**: Use the "Test Enter Current Settlement" context menu option
+5. **Check Input System**: Verify if project uses old or new Input System
+
+## Immediate Actions
+
+1. Check if SettlementInteractionManager GameObject exists in MapScene2
+2. Verify component references are properly assigned
+3. Enable debug logging and check console output
+4. Test the context menu function to isolate input vs logic issues

+ 89 - 0
ERROR_FIXES_SUMMARY.md

@@ -0,0 +1,89 @@
+# Fixed Errors and Warnings Summary
+
+## Issues Resolved ✅
+
+### 1. **CS0246 Error - Missing UIDocument Reference**
+**Problem:** `UIDocument` type not found in `TownSetupHelper.cs`  
+**Solution:** Added `using UnityEngine.UIElements;` directive
+
+### 2. **Broken GUID Reference in UXML**
+**Problem:** Invalid GUID reference causing PPtr errors  
+**Solution:** Simplified UXML header to remove problematic GUID references
+
+### 3. **CSS Property Warnings in TownUI.uss**
+**Problems and Solutions:**
+- `cursor: pointer` → Removed (not supported in Unity UI Toolkit)
+- `transform: scale(1.05)` → Changed to `scale: 1.05 1.05;` 
+- `font-style: italic` → Changed to `-unity-font-style: italic;`
+- `@media` queries → Simplified to regular CSS classes
+
+## Updated Files
+
+### TownSetupHelper.cs
+- ✅ Added missing `using UnityEngine.UIElements;`
+- ✅ Now properly references UIDocument type
+
+### TownUI.uxml  
+- ✅ Simplified header without problematic GUID references
+- ✅ Clean UXML structure that Unity can properly import
+
+### TownUI.uss
+- ✅ Removed unsupported `cursor` properties
+- ✅ Fixed `transform` to use Unity's `scale` property
+- ✅ Changed `font-style` to `-unity-font-style`
+- ✅ Simplified responsive design without `@media` queries
+- ✅ Removed `transition-duration` for better compatibility
+
+## Unity UI Toolkit Compatibility Notes
+
+### Supported Properties ✅
+- `scale: x y;` for scaling elements
+- `-unity-font-style: bold | italic | normal;` for font styling
+- Standard flex properties (justify-content, align-items, etc.)
+- Color and sizing properties
+- Border and padding properties
+
+### Unsupported Properties ❌
+- `cursor: pointer;` (no cursor control in UI Toolkit)
+- `transform: scale();` (use `scale:` instead)
+- `font-style:` (use `-unity-font-style:` instead)
+- `@media` queries (not supported)
+- `transition-duration` (limited animation support)
+
+## Testing Steps
+
+1. **Verify Compilation** ✅
+   - All C# errors should be resolved
+   - No more missing type references
+
+2. **Check UI Import** ✅  
+   - TownUI.uxml should import without PPtr errors
+   - TownUI.uss should show no warnings in Console
+
+3. **Test Visual Elements** ✅
+   - Buildings should display with proper colors
+   - Hover effects should work (scale change, border highlight)
+   - Text should display with proper styling
+
+## Code Quality Improvements
+
+### Error Prevention
+- Added proper `using` statements for all dependencies
+- Simplified asset references to avoid GUID conflicts
+- Used Unity-specific CSS properties throughout
+
+### Maintainability  
+- Cleaner CSS without browser-specific properties
+- Simplified responsive design approach
+- Better documentation of supported/unsupported features
+
+## Next Steps
+
+With these fixes, you should be able to:
+
+1. **Compile Successfully** - No more CS0246 errors
+2. **Import UI Assets** - No more broken PPtr references  
+3. **Style Elements Properly** - No more CSS warnings
+4. **Test the Town System** - Full functionality should work
+
+The town system is now ready for testing and further development without any compilation or import errors!

+ 195 - 0
MAP_SETTLEMENT_INTERACTION_GUIDE.md

@@ -0,0 +1,195 @@
+# MapScene2 Settlement Interaction Setup Guide
+
+## Overview
+This guide explains how to set up the settlement interaction system that allows players to enter towns and villages from the map scene.
+
+## Components Created
+
+### 1. SettlementInteractionManager.cs
+**Purpose**: Detects when TeamMarker is near settlements and handles town scene loading
+**Key Features**:
+- Detects TeamMarker proximity to settlements
+- Handles input for entering settlements
+- Sets up SettlementContext for scene transitions
+- Optional auto-enter when stationary
+- Configurable interaction distance and keys
+
+### 2. SettlementInteractionUI.cs
+**Purpose**: Displays UI prompts when near settlements
+**Key Features**:
+- Shows settlement name and interaction instructions
+- Automatically appears/disappears based on proximity
+- Customizable UI element names
+- Clean event-driven architecture
+
+### 3. UI Files
+- **SettlementInteractionUI.uxml**: UI layout for interaction prompts
+- **SettlementInteractionUI.uss**: Styling for the interaction UI
+
+## Setup Instructions
+
+### Step 1: Add to MapScene2
+1. Open your MapScene2 scene
+2. Create an empty GameObject called "SettlementInteractionManager"
+3. Add the `SettlementInteractionManager` component to it
+4. Configure the settings:
+   - **Team Marker**: Will auto-find "TeamMarker" GameObject
+   - **Interaction Distance**: 2.0 (how close to be to interact)
+   - **Enter Settlement Key**: E (key to press to enter)
+   - **Auto Enter On Stop**: Optional automatic entry
+   - **Town Scene Name**: "TownSceen" (your town scene name)
+
+### Step 2: Add Settlement Interaction UI
+1. Create another empty GameObject called "SettlementInteractionUI"
+2. Add a `UIDocument` component to it
+3. Assign the `SettlementInteractionUI.uxml` file to the UIDocument
+4. Add the `SettlementInteractionUI` component to it
+5. The component will automatically connect to the SettlementInteractionManager
+
+### Step 3: Configure TeamMarker
+Make sure your TeamMarker GameObject:
+- Is named "TeamMarker" (or manually assign in SettlementInteractionManager)
+- Has a Transform that moves around the map
+- Is positioned correctly relative to the map tiles
+
+### Step 4: Verify Map Data Integration
+The system requires:
+- MapMaker2 component in the scene
+- MapData with settlements properly generated
+- MapVisualizer for coordinate conversion
+
+## How It Works
+
+### Detection Flow
+1. **Position Tracking**: SettlementInteractionManager tracks TeamMarker position
+2. **Coordinate Conversion**: Converts world position to map tile coordinates
+3. **Settlement Check**: Searches for settlements within interaction distance
+4. **UI Update**: Shows/hides interaction prompt based on proximity
+5. **Input Handling**: Listens for interaction key press
+6. **Scene Transition**: Sets up SettlementContext and loads town scene
+
+### Settlement Context Setup
+When entering a settlement, the system:
+1. **Creates SettlementContext**: Persistent singleton for cross-scene data
+2. **Sets Settlement Data**: Name, type (town/village), position
+3. **Determines Harbor**: Checks nearby tiles for water
+4. **Generates Seed**: Consistent generation based on position and name
+5. **Loads Town Scene**: Transitions to town with proper context
+
+### Town Scene Integration
+The town scene will automatically:
+1. **Read SettlementContext**: Get settlement data from the persistent singleton
+2. **Configure Shops**: Set up appropriate shops for town vs village
+3. **Apply Names**: Use randomized shop names based on settlement
+4. **Handle Harbor**: Show/hide harbor based on hasHarbor setting
+
+## Configuration Options
+
+### SettlementInteractionManager Settings
+```csharp
+[Header("Settlement Detection")]
+public Transform teamMarker;              // Auto-finds "TeamMarker"
+public float interactionDistance = 2f;   // How close to interact
+public KeyCode enterSettlementKey = KeyCode.E;  // Interaction key
+public bool autoEnterOnStop = false;     // Auto-enter when stationary
+public float autoEnterDelay = 1f;        // Delay for auto-enter
+
+[Header("Scene Loading")]
+public string townSceneName = "TownSceen";  // Town scene to load
+
+[Header("Debug")]
+public bool enableDebugLogs = true;       // Enable debug console output
+```
+
+### SettlementInteractionUI Settings
+```csharp
+[Header("UI Element Names")]
+public string promptContainerName = "SettlementPrompt";
+public string settlementNameLabelName = "SettlementName";
+public string instructionLabelName = "InteractionInstruction";
+```
+
+## Testing
+
+### Manual Testing
+1. **Find Settlement**: Move TeamMarker near a town or village on the map
+2. **Check Proximity**: UI prompt should appear when close enough
+3. **Press Interaction Key**: Press E (or configured key) to enter
+4. **Verify Scene Load**: Should load town scene with correct settlement data
+5. **Check Town Configuration**: Verify shops match settlement type
+
+### Debug Features
+- **Enable Debug Logs**: Set `enableDebugLogs = true` for console output
+- **Test Enter Current Settlement**: Use context menu on SettlementInteractionManager
+- **Monitor Settlement Detection**: Watch console for proximity messages
+
+### Context Menu Testing
+Right-click SettlementInteractionManager component:
+- **Test Enter Current Settlement**: Enter currently nearby settlement
+
+## Troubleshooting
+
+### Common Issues
+
+1. **TeamMarker Not Found**
+   - Ensure GameObject is named "TeamMarker"
+   - Or manually assign in SettlementInteractionManager
+
+2. **No Settlement Detection**
+   - Check MapMaker2 is in scene and has MapData
+   - Verify settlements are generated in MapData
+   - Check interaction distance setting
+
+3. **UI Not Showing**
+   - Verify UIDocument has correct UXML file
+   - Check UI element names match configuration
+   - Ensure SettlementInteractionUI component is added
+
+4. **Town Scene Doesn't Load**
+   - Check town scene name is correct
+   - Verify scene is added to Build Settings
+   - Check console for SceneManager errors
+
+5. **Settlement Context Not Working**
+   - Ensure SettlementContext persists with DontDestroyOnLoad
+   - Check town scene has components that read SettlementContext
+   - Verify TownShopManager integration
+
+### Debug Console Messages
+When `enableDebugLogs = true`, you'll see:
+```
+[SettlementInteraction] Found TeamMarker automatically
+[SettlementInteraction] Connected to MapMaker2 - Map size: 150x150
+[SettlementInteraction] Near settlement: Riverside Town (Town)
+[SettlementInteraction] Entering settlement: Riverside Town (Town)
+[SettlementInteraction] SettlementContext configured: Riverside Town (Town) - Harbor: true
+[SettlementInteraction] Loading town scene: TownSceen
+```
+
+## Integration with Existing Systems
+
+### MapMaker2 Integration
+- Uses existing MapData and settlement generation
+- Leverages MapVisualizer for coordinate conversion
+- Works with current team marker placement system
+
+### SettlementContext Integration
+- Extends existing town/village distinction system
+- Integrates with TownShopManager for shop configuration
+- Works with existing randomized shop names
+
+### Scene Management Integration
+- Uses existing "Return to Map" functionality
+- Maintains team position between scene transitions
+- Preserves game state through GameStateManager
+
+## Future Enhancements
+
+1. **Visual Indicators**: Add markers or highlights on settlements
+2. **Settlement Info**: Show settlement details before entering
+3. **Fast Travel**: Quick travel between discovered settlements
+4. **Settlement Reputation**: Track relationship with each settlement
+5. **Custom Interaction Range**: Per-settlement interaction distances
+6. **Animation**: Smooth transitions and UI animations
+
+This system provides a solid foundation for map-to-settlement transitions while integrating seamlessly with your existing town and village systems.

+ 131 - 0
MEDIEVAL_TOWN_SETUP_GUIDE.md

@@ -0,0 +1,131 @@
+# Medieval Town Scene Setup Guide
+
+## Overview
+This guide explains how to set up the new medieval-style town scene with working interactive shops.
+
+## Visual Improvements Made
+
+### 1. Medieval Layout
+- **Town Walls**: Added stone walls at top and bottom to create authentic medieval town feel
+- **Districts**: Organized buildings into logical areas:
+  - **Upper District**: Castle, Noble Houses, Adventurer's Guild
+  - **Market District**: Central market square with all shops around it
+  - **Lower District**: Inn, Harbor, General Store, Common Houses
+
+### 2. Interactive Building Indicators
+- **Shop Banners**: Red banners with shop type labels ("WEAPONS", "ARMOR", etc.)
+- **Interaction Banners**: Gold banners for special buildings ("Click to Enter")
+- **Border Effects**: Gold borders on all interactable buildings
+- **Hover Effects**: Buildings scale up and change colors when hovered
+
+### 3. Medieval Color Scheme
+- **Background**: Rich brown medieval ground color
+- **Buildings**: 
+  - Weapon Shop: Deep red (forge theme)
+  - Armor Shop: Steel blue (metalwork theme)
+  - Potion Shop: Purple (mystical theme)
+  - General Store: Orange (trade theme)
+  - Castle: Stone gray
+  - Inn: Warm brown
+  - Harbor: Navy blue
+
+## Technical Fixes Made
+
+### 1. Fixed Shop Click Events
+- **Problem**: Shops weren't clickable due to missing initialization
+- **Solution**: 
+  - Fixed TownManager to properly initialize TownShopManager
+  - Added automatic shop creation if none exist
+  - Enhanced click handler registration with better error checking
+  - Added debugging to help identify UI element issues
+
+### 2. Improved Error Handling
+- Added comprehensive debugging for UI element detection
+- Better error messages when components are missing
+- Automatic fallback shop creation
+
+### 3. Enhanced Visual Feedback
+- Interactable buildings now have clear visual indicators
+- Hover effects show building names in gold
+- Banner system clearly identifies shop types
+
+## How to Set Up Town Scene
+
+### 1. Scene Setup
+1. Open `TownSceen.unity` scene
+2. Create empty GameObject called "TownManager"
+3. Add `TownManager` component to it
+4. Add `TownShopManager` component to it
+5. Add `TownSetupHelper` component to it
+
+### 2. UI Setup
+1. Create Canvas with UI Document component
+2. Assign `TownUI.uxml` to the UI Document
+3. Link the UI Document to TownManager's `townUI` field
+4. Link the UI Document to TownShopManager's `townUI` field
+
+### 3. Camera Setup
+1. Position camera to show the entire town grid
+2. Set camera to Orthographic if desired for classic RPG feel
+
+### 4. Testing
+1. Enter Play Mode
+2. Check Console for initialization messages:
+   - "Registered shop: [ShopName] -> [UIElementName]"
+   - "✓ Setup click handler for [ElementName]"
+3. Click on shops with banners to test interaction
+4. Check that shop UI opens with buy/sell options
+
+## Shop Types Available
+
+1. **Weapon Shop** ("The Forge")
+   - Sells swords, axes, bows, daggers
+   - Red building with weapon banner
+
+2. **Armor Shop** ("Ironclad Armory")
+   - Sells helmets, chestplates, boots, shields
+   - Blue building with armor banner
+
+3. **Potion Shop** ("The Bubbling Cauldron")
+   - Sells health potions, mana potions, buff potions
+   - Purple building with potion banner
+
+4. **General Store** ("Pete's General Goods")
+   - Sells miscellaneous items, tools, supplies
+   - Orange building with general store banner
+
+## Future Enhancements Possible
+
+1. **Building Animations**: Add smoke from chimneys, moving flags
+2. **NPCs**: Add walking townspeople
+3. **Day/Night Cycle**: Change building lighting based on time
+4. **Weather Effects**: Add rain, snow overlay effects
+5. **Building Interiors**: Create interior scenes for larger buildings
+6. **Quest Board**: Implement quest system in Adventurer's Guild
+7. **Inn Services**: Add rest, save, and heal options
+8. **Harbor Travel**: Add ship travel to other towns
+
+## Troubleshooting
+
+### Shops Not Clickable
+1. Check Console for "Could not find UI element" warnings
+2. Verify UI Document is properly assigned
+3. Ensure TownShopManager is attached to same GameObject as TownManager
+4. Run "Setup Sample Town" from TownSetupHelper context menu
+
+### Visual Issues
+1. Verify TownUI.uss is properly linked in UXML file
+2. Check that interactable-building class is being applied
+3. Ensure banner elements are properly positioned
+
+### Missing Items in Shops
+1. Run ItemCreatorHelper to generate sample items
+2. Check Resources folder for created ScriptableObjects
+3. Verify shop inventories are properly loaded
+
+## Files Modified
+- `TownUI.uxml`: Complete medieval layout redesign
+- `TownUI.uss`: New medieval styling with banners and effects
+- `TownShopManager.cs`: Fixed initialization and click handling
+- `TownManager.cs`: Proper integration with shop manager
+- All shop-related scripts: Enhanced error handling and debugging

+ 3 - 0
ProjectSettings/EditorBuildSettings.asset

@@ -17,6 +17,9 @@ EditorBuildSettings:
   - enabled: 1
     path: Assets/Scenes/BattleScene.unity
     guid: 99c9720ab356a0642a771bea13969a05
+  - enabled: 1
+    path: Assets/Scenes/TownSceen.unity
+    guid: 723fd2a20c743e3408fc58ddacf430c8
   m_configObjects:
     com.unity.input.settings.actions: {fileID: -944628639613478452, guid: 052faaac586de48259a63d0c4782560b, type: 3}
     com.unity.xr.management.loader_settings: {fileID: 11400000, guid: fe07304d36c3c054bb90adfdfac5b312, type: 2}

+ 68 - 0
SETTLEMENT_INTERACTION_OPTIMAL_SETUP.md

@@ -0,0 +1,68 @@
+# Settlement Interaction Manager Optimal Settings
+
+## SettlementInteractionManager Settings (Image 2)
+
+### Settlement Detection ✅
+- **Team Marker**: TeamMarker (Transform) ✅ CORRECT
+- **Interaction Distance**: 2 ✅ CORRECT
+- **Enter Settlement Key**: E ✅ CORRECT  
+- **Auto Enter On Stop**: Unchecked ✅ CORRECT (manual entry only)
+- **Auto Enter Delay**: 1 ✅ CORRECT
+
+### UI ✅
+- **Interaction Prompt**: SettlementInteractionUI ✅ CORRECT
+
+### Scene Loading ✅
+- **Town Scene Name**: TownSceen ✅ CORRECT
+
+### Debug ✅
+- **Enable Debug Logs**: Checked ✅ CORRECT
+
+## Components to Keep vs Remove
+
+### ✅ KEEP these components:
+1. **SettlementInteractionManager** (core functionality)
+2. **SettlementInteractionCompleteFix** (fixes detection issues)
+
+### ❌ REMOVE these components (redundant):
+3. **SettlementInteractionFixer** 
+4. **SettlementDetectionHotfix**
+
+## SettlementInteractionUI GameObject Setup
+
+### ✅ KEEP these components:
+1. **Transform** (position)
+2. **UI Document** (UI Toolkit)
+3. **SettlementInteractionUI** (script)
+4. **SettlementUIBridge** (connects GameObject to UI)
+
+## Expected Behavior After Cleanup
+
+1. **Console Output**: Should show detection messages when walking near settlements
+2. **UI Updates**: Settlement name should change when entering different settlements
+3. **UI Visibility**: Should only show when near settlements (not constantly)
+4. **E Key**: Should work to enter settlements
+5. **Scene Loading**: Should transition to TownSceen smoothly
+
+## Debug Commands
+
+- **F9**: Force fix settlement references
+- **F10**: Test detailed settlement detection  
+- **F11**: Test manual settlement entry
+- **F12**: Test scene loading
+
+## Troubleshooting
+
+If still not working after cleanup:
+1. Check console for error messages
+2. Verify TeamMarker is at correct world position
+3. Check that settlements exist in MapData
+4. Ensure TownSceen is in Build Settings
+
+## Quick Test
+
+1. Remove redundant components
+2. Run scene
+3. Move TeamMarker to position (122, 71) - known town location
+4. UI should show town name and "Press E to enter Town"
+5. Press E should load TownSceen

+ 119 - 0
SETTLEMENT_INTERACTION_TROUBLESHOOTING.md

@@ -0,0 +1,119 @@
+# Settlement Interaction Debugging and Setup Guide
+
+## Problem
+Settlement interaction UI shows but E key doesn't work to enter settlements.
+
+## Quick Diagnosis
+
+### Step 1: Add the Debugger
+1. Add `SettlementInteractionDebugger.cs` component to any GameObject in MapScene2
+2. Run the scene and check the console output
+3. The debugger will show exactly what's missing
+
+### Step 2: Common Issues and Solutions
+
+#### Issue A: No SettlementInteractionManager in Scene
+**Symptoms**: Debugger shows "❌ SettlementInteractionManager NOT FOUND!"
+**Solution**:
+1. Create empty GameObject in MapScene2 named "SettlementInteractionManager"
+2. Add `SettlementInteractionManager` component to it
+3. Configure settings:
+   - Team Marker: Will auto-find "TeamMarker"
+   - Interaction Distance: 2.0
+   - Enter Settlement Key: E
+   - Town Scene Name: "TownSceen"
+   - Enable Debug Logs: true
+
+#### Issue B: Missing UI Setup
+**Symptoms**: Logic works but no UI shows
+**Solution**:
+1. Create GameObject named "SettlementInteractionUI" 
+2. Add `UIDocument` component
+3. Add `SettlementInteractionUI` component
+4. Set UI Document asset to `SettlementInteractionUI.uxml`
+5. Make sure UXML file exists in `Assets/Resources/UI/MapScene/`
+
+#### Issue C: TeamMarker Not Found
+**Symptoms**: Debugger shows "❌ TeamMarker GameObject not found!"
+**Solution**:
+1. Make sure GameObject named "TeamMarker" exists in scene
+2. Or manually assign teamMarker reference in SettlementInteractionManager
+
+#### Issue D: MapData Not Available
+**Symptoms**: "Settlements count: 0" or MapData null
+**Solution**:
+1. Ensure MapMaker2 component exists in scene
+2. Ensure map has been generated with settlements
+3. Check that MapData.GetAllSettlements() returns settlements
+
+#### Issue E: Input System Issues
+**Symptoms**: Manual entry works but E key doesn't
+**Solution**:
+1. Check if project uses new Input System (Package Manager)
+2. If using new Input System, might need to update input handling
+3. Test with debugger's "Test Input Detection" to see if keys register
+
+### Step 3: Testing Process
+
+1. **Add Debugger**: Put SettlementInteractionDebugger on any GameObject
+2. **Run Scene**: Check console for component diagnosis
+3. **Move TeamMarker**: Move near settlements and watch debug output
+4. **Test Keys**: Press F1 to test detection, F2 to test manual entry
+5. **Check Console**: Look for debug messages when moving near settlements
+
+### Step 4: Verification
+
+When working correctly, you should see:
+1. ✅ All components found in diagnosis
+2. Debug messages when moving TeamMarker near settlements
+3. UI prompt appears/disappears based on proximity
+4. E key successfully loads town scene
+5. Settlement context properly configured
+
+## Quick Fix Commands
+
+### Force Enable All Debug Logging
+```csharp
+// In Unity Console or attached to a button
+var manager = FindFirstObjectByType<SettlementInteractionManager>();
+if (manager != null) manager.enableDebugLogs = true;
+```
+
+### Manual Settlement Entry Test
+```csharp
+// Test if the logic works without input
+var manager = FindFirstObjectByType<SettlementInteractionManager>();
+if (manager != null) manager.TestEnterCurrentSettlement();
+```
+
+### Check Current Settlement Detection
+```csharp
+// See if any settlement is currently detected
+var manager = FindFirstObjectByType<SettlementInteractionManager>();
+var settlement = manager?.GetCurrentNearbySettlement();
+Debug.Log($"Current settlement: {settlement?.name ?? "None"}");
+```
+
+## Debug UI Overlay
+
+The SettlementInteractionDebugger provides an on-screen debug panel that shows:
+- Current settlement detection status
+- TeamMarker position
+- Quick test buttons
+- Real-time component status
+
+Toggle with `enableDebugOverlay = true` in the debugger component.
+
+## Expected Debug Output
+
+When working correctly, moving TeamMarker near a settlement should show:
+```
+[SettlementInteraction] Near settlement: Riverside Town (Town)
+[SettlementInteraction] SettlementContext configured: Riverside Town (Town) - Harbor: true
+[SettlementInteraction] Loading town scene: TownSceen
+```
+
+When the E key is pressed near a settlement:
+```
+[SettlementInteraction] Entering settlement: Riverside Town (Town)
+```

+ 53 - 0
SETTLEMENT_UI_BRIDGE_FIX.md

@@ -0,0 +1,53 @@
+# Settlement UI Bridge Fix Guide
+
+## Problem Identified
+You have two separate GameObjects:
+1. **SettlementInteractionManager GameObject** - has SettlementInteractionManager + SettlementUIBridge
+2. **SettlementInteractionUI GameObject** - has UIDocument + SettlementInteractionUI component
+
+The SettlementUIBridge is trying to find SettlementInteractionUI on the same GameObject, but they're on different GameObjects!
+
+## Solution: Move SettlementUIBridge
+
+### Step 1: Remove SettlementUIBridge from SettlementInteractionManager GameObject
+1. Select the **SettlementInteractionManager** GameObject in the hierarchy
+2. Find the **SettlementUIBridge** component
+3. Right-click on it and select **Remove Component**
+
+### Step 2: Add SettlementUIBridge to SettlementInteractionUI GameObject
+1. Select the **SettlementInteractionUI** GameObject in the hierarchy
+2. Click **Add Component**
+3. Search for **SettlementUIBridge** and add it
+4. The component will automatically find the SettlementInteractionUI on the same GameObject
+
+### Step 3: Verify Setup
+After making this change, when you play the game you should see:
+```
+[UIBridge] Connected to SettlementInteractionUI
+```
+
+### Step 4: Test Settlement Detection
+1. Move your TeamMarker near a settlement
+2. The UI should now properly show/hide based on proximity
+3. The settlement name should display the actual settlement name instead of "Settlement Name"
+
+## Alternative Solution: Move SettlementInteractionUI Component
+
+If you prefer to keep everything on the SettlementInteractionManager GameObject:
+
+1. Select the **SettlementInteractionUI** GameObject
+2. Copy the **UIDocument** component settings (note the UXML file reference)
+3. Copy the **SettlementInteractionUI** component settings
+4. Delete the **SettlementInteractionUI** GameObject
+5. On the **SettlementInteractionManager** GameObject:
+   - Add **UIDocument** component
+   - Set the UXML file reference
+   - Add **SettlementInteractionUI** component
+   - Configure the component settings
+
+## Expected Result
+After either fix, you should see:
+- `[UIBridge] Connected to SettlementInteractionUI` in console
+- Settlement UI shows actual settlement names
+- UI appears/disappears when moving near/away from settlements
+- E key works to enter settlements

+ 57 - 0
SHOP_UI_FIX_GUIDE.md

@@ -0,0 +1,57 @@
+# Shop UI Issue Fix
+
+## Problem Identified
+The shop interaction was working (you saw "Opening Ironclad Armory" in the logs), but the shop UI wasn't appearing because:
+
+1. **Duplicate Managers**: You had two TownManager objects causing conflicts
+2. **Complex UI Failure**: The original TownShopUI was trying to load a missing UXML file and failing silently
+
+## Solution Applied
+
+### 1. Fixed Duplicate Managers
+- **Issue**: Two TownManager objects in the scene hierarchy
+- **Fix**: Delete the duplicate TownManager, keep only one with the shop child objects
+
+### 2. Created Simple Shop UI
+- **New File**: `SimpleTownShopUI.cs` - A working, simplified shop interface
+- **Purpose**: Displays shop name, inventory count, player money, and close button
+- **Benefit**: Proves that the shop interaction system is working
+
+### 3. Updated TownManager
+- **Fixed**: Added proper `OnBuildingClicked` method
+- **Fixed**: Now uses `SimpleTownShopUI` instead of the broken `TownShopUI`
+- **Fixed**: Proper UI cleanup when shop is closed
+
+## How to Test
+
+1. **Remove Duplicate Manager**:
+   - In Unity Hierarchy, find the duplicate TownManager
+   - Delete the one that doesn't have child shop objects
+   - Keep the one with WeaponShop, ArmorShop, etc. as children
+
+2. **Test Shop Interaction**:
+   - Play the scene
+   - Click on any shop (Weapon Shop, Armor Shop, etc.)
+   - You should see a brown dialog box with gold borders
+   - The dialog shows shop name, inventory count, and player money
+
+3. **Expected Result**:
+   - Shop dialog appears immediately when clicked
+   - You can close the shop with the "Close Shop" button
+   - Console shows "Simple shop UI created and displayed!"
+
+## Next Steps
+
+Once basic interaction is confirmed working:
+
+1. **Fix Complex UI**: Repair the full `TownShopUI.cs` for complete buy/sell functionality
+2. **Visual Polish**: Add more medieval visual elements
+3. **Full Features**: Implement complete shop inventory management
+
+## Files Modified
+
+- `TownManager.cs`: Added `OnBuildingClicked` method, uses `SimpleTownShopUI`
+- `SimpleTownShopUI.cs`: New simplified shop interface (CREATED)
+- Fixed click event routing between TownShopManager and TownManager
+
+The shops should now be clickable and show a working (though simplified) interface!

+ 111 - 0
TOWNSHOPUI_FIX_SUMMARY.md

@@ -0,0 +1,111 @@
+# TownShopUI Fix Summary
+
+## Problem Resolved
+The TownShopUI.cs file was completely corrupted with 1053 lines of broken code containing over 25 compilation errors. The file has been completely rewritten from scratch using the correct Unity UI Toolkit patterns and proper TeamCharacter integration.
+
+## Key Changes Made
+
+### 1. Fixed GameStateManager Integration
+- **Before**: Used non-existent `gameStateManager.playerTeam.teamMembers`
+- **After**: Uses `GameStateManager.Instance.savedTeam` (correct property)
+- **Impact**: Customer dropdown now properly loads team members
+
+### 2. Corrected TeamCharacter Property Usage
+- **Before**: Used incorrect properties like `characterName`, `weaponItems`, `armorItems`
+- **After**: Uses correct properties: `name`, `weapons`, `armor`, `miscItems`, `gold`, `silver`, `copper`
+- **Impact**: Money display and inventory access now work correctly
+
+### 3. Fixed Item Type Checking
+- **Before**: Referenced non-existent `ConsumableItem` class
+- **After**: Uses `MiscellaneousItem` with `ItemType.Consumable` check
+- **Impact**: Category filtering now works properly
+
+### 4. Resolved Unity UI Toolkit API Issues
+- **Before**: Attempted to modify read-only `rootVisualElement`
+- **After**: Properly queries existing UI elements using correct names
+- **Impact**: UI initialization no longer crashes
+
+### 5. Added Proper UXML/USS Support
+- **Created**: `TownShopUI.uxml` with all required UI elements (shop-container, customer-dropdown, buy-tab, sell-tab, etc.)
+- **Created**: `TownShopUI.uss` with medieval-themed styling
+- **Added**: Resources folder copies for runtime loading
+- **Impact**: Complete visual shop interface with proper styling
+
+### 6. Updated TownManager Integration
+- **Before**: Used SimpleTownShopUI as fallback
+- **After**: Uses fixed TownShopUI with proper UIDocument loading
+- **Impact**: Players now get the full shop experience instead of basic fallback
+
+## Current Limitations Noted
+
+### Inventory System Gap
+The current system has a fundamental limitation: TeamCharacter stores item names as strings (`List<string> weapons`, `List<string> armor`), but the shop UI needs actual Item objects to display detailed information and handle selling.
+
+**Current Behavior**: 
+- Buying items works (adds item names to appropriate string lists)
+- Selling items shows empty list with debug warnings
+- Player inventory display is limited
+
+**Future Enhancement Needed**:
+- Implement ItemDatabase system to convert item names back to Item objects
+- This would enable full selling functionality and proper inventory display
+
+## Files Modified/Created
+
+### Modified Files:
+1. `Assets/Scripts/Town/TownShopUI.cs` - Completely rewritten (501 lines, clean code)
+2. `Assets/Scripts/Town/TownManager.cs` - Updated to use new TownShopUI
+
+### Created Files:
+1. `Assets/UI/TownShopUI.uxml` - Complete shop interface layout
+2. `Assets/UI/TownShopUI.uss` - Medieval-themed shop styling  
+3. `Assets/Resources/UI/TownShopUI.uxml` - Runtime loadable copy
+4. `Assets/Resources/UI/TownShopUI.uss` - Runtime loadable copy
+
+## Testing Status
+
+### ✅ Compilation Status: 
+- **All errors resolved** (0 compilation errors)
+- Clean integration with existing codebase
+- Proper Unity UI Toolkit compliance
+
+### ✅ Integration Status:
+- GameStateManager integration working
+- TeamCharacter property access correct
+- TownShop methods properly called
+- UI event handling implemented
+
+### 🔄 Functional Status:
+- **Shop Opening**: Should work (UI displays, customer selection)
+- **Item Browsing**: Should work (shop inventory display, filtering, search)
+- **Buying Items**: Should work (money deduction, item addition to inventory)
+- **Selling Items**: Limited (shows empty list due to string→Item conversion need)
+- **Visual Experience**: Enhanced with medieval styling and proper layout
+
+## Next Steps for User
+
+1. **Test the Shop System**:
+   - Open Unity and play the town scene
+   - Click on shop buildings to verify the new UI appears
+   - Test buying items to confirm money transactions work
+   - Verify customer dropdown shows team members
+
+2. **Handle Duplicate TownManager** (if issue persists):
+   - Check Unity scene hierarchy for multiple TownManager objects
+   - Remove any duplicates, keeping only one TownManager in the scene
+
+3. **Optional Future Enhancement**:
+   - Implement ItemDatabase for full selling functionality
+   - This would convert item name strings back to Item objects
+   - Enables complete buy/sell cycle with detailed item information
+
+## Summary
+
+The corrupted TownShopUI has been completely rebuilt with:
+- ✅ Proper Unity UI Toolkit integration
+- ✅ Correct GameStateManager and TeamCharacter property usage  
+- ✅ Medieval-themed visual design
+- ✅ Full buying functionality
+- ⚠️ Selling limited by current inventory system architecture
+
+The shop system is now functional for buying items and provides a much better visual experience than the previous SimpleTownShopUI fallback.

+ 138 - 0
TOWN_QUICK_SETUP.md

@@ -0,0 +1,138 @@
+# Town System Quick Setup Guide
+
+## What Has Been Created
+
+### Core Scripts
+✅ **TownManager.cs** - Main town controller  
+✅ **TownShopManager.cs** - UI interaction handler  
+✅ **TownBuilding.cs** - Base building class  
+✅ **TownShop.cs** - Shop logic and inventory  
+✅ **TownShopUI.cs** - Complete shop interface  
+
+### UI Assets  
+✅ **TownUI.uxml** - Main town visual layout  
+✅ **TownUI.uss** - Town styling  
+
+### Helper Scripts
+✅ **TownSetupHelper.cs** - Auto-configuration tool  
+✅ **ItemCreatorHelper.cs** - Sample item creation  
+
+## Quick Setup Steps
+
+### 1. Create Sample Items (Editor Only)
+1. In Unity Editor, go to **RPG Tools > Create Sample Items**
+2. This creates weapons, armor, potions, and tools in Resources/Items/
+
+### 2. Setup Town Scene
+1. Open the existing `TownScene.unity` 
+2. Create empty GameObject "TownManager"
+3. Add `TownManager` component
+4. Create UI Document GameObject 
+5. Assign `TownUI.uxml` to UI Document
+6. Link UI Document to TownManager's `townUI` field
+
+### 3. Auto-Configure Shops
+1. Add `TownSetupHelper` component to TownManager
+2. In Inspector, click **Setup Sample Town**
+3. Click **Setup Shop Manager** 
+4. This creates all shop GameObjects with proper configuration
+
+### 4. Test the System
+1. Play the scene
+2. Click on colored building squares to open shops
+3. Buy/sell items with different characters
+4. Money and inventory persist between shop visits
+
+## Visual Layout
+
+The town uses a grid layout with:
+- **Red squares** = Weapon Shop  
+- **Blue squares** = Armor Shop
+- **Green squares** = Potion Shop  
+- **Orange squares** = General Store
+- **Purple squares** = Adventurer's Guild (coming soon)
+- **Light blue squares** = Harbor (coming soon)
+- **Tan squares** = Inn (coming soon)
+- **Brown strips** = Roads
+
+## Shop Features
+
+### Weapon Shop - "The Forge"
+- Sells swords, axes, bows, daggers
+- 30% markup on base prices
+- Accepts weapon trade-ins at 60% value
+
+### Armor Shop - "Ironclad Armory"  
+- Sells helmets, chest armor, accessories
+- 25% markup on base prices
+- Accepts armor trade-ins at 60% value
+
+### Potion Shop - "The Bubbling Cauldron"
+- Sells health/mana potions, antidotes
+- 40% markup (specialized goods)
+- Accepts consumable trade-ins at 50% value
+
+### General Store - "Pete's General Goods"
+- Sells basic weapons, armor, tools, misc items
+- 20% markup (competitive prices)
+- Accepts most items at 65% value
+
+## Currency System
+- **1 Gold = 10 Silver = 100 Copper**
+- Characters start with varied amounts of money
+- Automatic currency conversion when buying/selling
+- Money displays update in real-time
+
+## Next Steps
+
+### Immediate Improvements
+1. **Add More Items**: Create specialized weapons and armor
+2. **Polish UI**: Improve shop interface styling  
+3. **Add Tooltips**: Show item stats on hover
+4. **Sound Effects**: Add audio feedback for transactions
+
+### Future Features
+1. **Adventurer's Guild**: Quest system and job board
+2. **Harbor System**: Travel to other towns/locations
+3. **Inn Functionality**: Rest, heal, save progress
+4. **NPC Dialogue**: Conversations with shopkeepers
+5. **Dynamic Events**: Special sales, traveling merchants
+
+## Troubleshooting
+
+### Common Issues
+- **Shops don't open**: Ensure TownShopManager has shop references
+- **No items in shops**: Run "Setup Sample Town" again
+- **UI not responsive**: Check that UXML/USS files are properly linked
+- **Money not saving**: Verify GameStateManager integration
+
+### Debug Tools
+- Use TownSetupHelper context menu options
+- Check console for setup completion messages  
+- Verify item loading in Resources/Items/ folders
+
+## Integration Notes
+
+This town system integrates seamlessly with your existing:
+- **TeamCharacter system**: Uses gold/silver/copper fields
+- **Save system**: Works with GameStateManager  
+- **Scene management**: Proper transitions to/from map
+- **Item system**: Compatible with WeaponItem, ArmorItem, etc.
+
+The system is designed to be:
+- **Modular**: Easy to add new building types
+- **Extensible**: Simple to add new shop features  
+- **Maintainable**: Clear separation of concerns
+- **User-friendly**: Intuitive click-to-interact interface
+
+## Success Indicators
+
+You'll know the system is working when:
+✅ Town scene loads with colored building grid  
+✅ Clicking buildings opens appropriate shop interfaces  
+✅ Shop inventories populate with items automatically  
+✅ Buy/sell transactions update money and inventory  
+✅ Money changes persist when switching between shops  
+✅ System integrates smoothly with existing save/load
+
+The town system provides a solid foundation that can grow with your game's needs!

+ 244 - 0
TOWN_SYSTEM_GUIDE.md

@@ -0,0 +1,244 @@
+# Town System Implementation Guide
+
+## Overview
+This guide explains how to set up a complete interactive town system with shops, an adventurer's guild, harbor, and other buildings. The system uses Unity UI Toolkit (UXML/USS) for all interfaces and provides a modular approach to town management.
+
+## Components Created
+
+### Core Town System
+- **TownManager.cs**: Main town controller and team data management
+- **TownShopManager.cs**: Handles UI interactions and shop opening logic
+- **TownBuilding.cs**: Base class for all interactive town buildings
+- **TownShop.cs**: Specialized shop buildings with inventory and pricing
+- **TownShopUI.cs**: Complete shop interface with buy/sell functionality
+
+### UI Assets
+- **TownUI.uxml**: Main town visual layout with grid-based building system
+- **TownUI.uss**: Comprehensive styling for the town interface
+- **TownShopUI.uxml**: Shop interface (created programmatically if not found)
+
+## Setup Instructions
+
+### 1. Scene Setup
+1. Open or create the `TownScene.unity`
+2. Create an empty GameObject called "TownManager"
+3. Add the `TownManager` component to it
+4. Create a UI Document GameObject and assign the `TownUI.uxml` file
+5. Link the UI Document to the TownManager's `townUI` field
+
+### 2. Shop Configuration
+1. Create empty GameObjects for each shop type:
+   - "WeaponShop" 
+   - "ArmorShop"
+   - "PotionShop" 
+   - "GeneralStore"
+
+2. Add the `TownShop` component to each shop GameObject
+
+3. Configure each shop:
+   ```csharp
+   // Weapon Shop
+   shopType = ShopType.Weapons
+   shopkeeperName = "Gareth the Smith"
+   profitMargin = 1.3f (30% markup)
+   
+   // Armor Shop  
+   shopType = ShopType.Armor
+   shopkeeperName = "Miranda the Armorer"
+   profitMargin = 1.25f (25% markup)
+   
+   // Potion Shop
+   shopType = ShopType.Potions
+   shopkeeperName = "Elias the Alchemist" 
+   profitMargin = 1.4f (40% markup)
+   
+   // General Store
+   shopType = ShopType.General
+   shopkeeperName = "Old Pete"
+   profitMargin = 1.2f (20% markup)
+   ```
+
+### 3. Shop Manager Setup
+1. Create an empty GameObject called "ShopManager"
+2. Add the `TownShopManager` component
+3. Assign all shop GameObjects to the `allShops` array
+4. Link the UI Document to the `townUI` field
+
+### 4. Item Configuration
+The shops will automatically load items from `Resources/Items/` folders:
+- `Resources/Items/Weapons/` - Weapon items
+- `Resources/Items/Armor/` - Armor items  
+- `Resources/Items/Miscellaneous/` - Potions and misc items
+
+### 5. Building Visual Configuration
+The town uses a CSS Grid-like layout defined in the UXML:
+
+```xml
+<!-- Buildings are positioned in rows -->
+<ui:VisualElement name="Row1" class="town-row">
+    <ui:VisualElement name="WeaponShop" class="town-building weapon-shop">
+        <ui:Label text="Weapon Shop" class="building-label" />
+    </ui:VisualElement>
+    <!-- ... more buildings -->
+</ui:VisualElement>
+```
+
+Buildings are styled with CSS classes in the USS file:
+- `.weapon-shop` - Red building for weapons
+- `.armor-shop` - Blue building for armor
+- `.potion-shop` - Green building for potions
+- `.general-shop` - Orange building for general goods
+
+## Features Implemented
+
+### Shop System
+- **Dynamic Pricing**: Each shop applies a configurable profit margin to base item prices
+- **Buy/Sell System**: Players can buy items from shops and sell items back at reduced prices
+- **Inventory Filtering**: Shops only accept items of appropriate types
+- **Search and Categorization**: Shop UI includes search and category filters
+- **Multiple Characters**: Support for multi-character teams with individual money
+
+### Visual Town Layout
+- **Grid-Based Design**: Buildings arranged in a clear grid with roads between
+- **Interactive Buildings**: Click to enter shops or interact with special buildings
+- **Color-Coded Buildings**: Different building types have distinct colors
+- **Hover Effects**: Buildings highlight when hovering
+- **Responsive Design**: Layout adapts to different screen sizes
+
+### Special Buildings (Coming Soon)
+- **Adventurer's Guild**: Quest system and job board
+- **Harbor**: Travel to other locations by sea
+- **Inn**: Rest, healing, and save game functionality
+- **Houses**: NPC interactions and side quests
+
+## Item Creation
+
+### Creating New Items
+1. Right-click in Project window
+2. Go to Create > RPG > Items > [Type]
+3. Configure the item properties:
+   ```csharp
+   itemName = "Iron Sword"
+   description = "A sturdy iron blade"
+   goldCost = 25
+   silverCost = 0
+   copperCost = 0
+   rarity = ItemRarity.Common
+   ```
+
+### Adding Items to Shops
+Items are automatically added to appropriate shops based on their `ItemType`:
+- `ItemType.Weapon` → Weapon Shop
+- `ItemType.Armor` → Armor Shop  
+- `ItemType.Consumable` → Potion Shop
+- `ItemType.Miscellaneous` → General Store
+
+You can also manually add items to a shop's `baseInventory` list.
+
+## Shop Economics
+
+### Pricing System
+- **Base Price**: Set in the Item ScriptableObject
+- **Shop Markup**: Configurable per shop (typically 20-40%)
+- **Sell-back Rate**: Players get 60% of base price when selling
+- **Currency**: Gold/Silver/Copper system (1g = 10s = 100c)
+
+### Example Pricing
+```
+Iron Sword (Base: 25g)
+- Weapon Shop: 32g 5s (30% markup)  
+- Sell back: 15g (60% of base)
+
+Health Potion (Base: 3g)
+- Potion Shop: 4g 2s (40% markup)
+- Sell back: 1g 8s (60% of base)
+```
+
+## Integration with Existing Systems
+
+### Team Character System
+The town system integrates with the existing `TeamCharacter` class:
+- Reads money from `gold`, `silver`, `copper` fields
+- Adds purchased items to `weapons`, `armor`, `miscItems` lists
+- Removes sold items from character inventories
+
+### Save System
+Team data is automatically saved through the existing `GameStateManager`:
+- Money changes persist between scenes
+- Inventory changes are maintained
+- Shop restock timers are preserved
+
+### Scene Transitions
+- Return to map via "Return to Map" button
+- Automatic save when leaving town
+- Team data transfers seamlessly
+
+## Customization Options
+
+### Visual Theming
+Modify `TownUI.uss` to change:
+- Building colors and styles
+- Layout and spacing
+- Fonts and text styling
+- Hover and interaction effects
+
+### Shop Behavior
+Adjust shop properties:
+- `profitMargin`: How much markup shops apply
+- `sellbackRate`: How much players get when selling
+- `maxInventorySize`: Maximum items per shop
+- `restockDaily`: Whether shops restock over time
+
+### Building Layout
+Edit `TownUI.uxml` to:
+- Add or remove buildings
+- Change building positions
+- Modify the grid layout
+- Add new building types
+
+## Troubleshooting
+
+### Common Issues
+1. **Shops not opening**: Ensure TownShopManager is properly configured with shop references
+2. **Items not loading**: Check that items are placed in correct Resources folders
+3. **UI not displaying**: Verify UXML and USS files are properly linked
+4. **Money not updating**: Ensure team data is properly loaded in TownManager
+
+### Debug Tips
+- Check console for setup completion messages
+- Use "Check Shop Setup" context menu on shops
+- Verify team data loading in TownManager Start()
+- Test with sample items if custom items aren't working
+
+## Future Enhancements
+
+### Planned Features
+- **Quest System**: Adventurer's Guild with dynamic quests
+- **NPC Dialogue**: Conversations with shopkeepers and townspeople
+- **Day/Night Cycle**: Different shops and activities based on time
+- **Random Events**: Special sales, traveling merchants, etc.
+- **Building Upgrades**: Shops can be improved over time
+
+### Extension Points
+The system is designed for easy extension:
+- Add new `BuildingType` values for new building types
+- Create specialized `TownBuilding` subclasses
+- Implement additional shop types with custom behavior
+- Add new UI panels for different interactions
+
+## Code Architecture
+
+### Key Classes
+- `TownManager`: Central coordinator, loads team data
+- `TownShopManager`: UI event handling and shop interaction
+- `TownBuilding`: Base building class with click handling
+- `TownShop`: Shop-specific logic and inventory management
+- `TownShopUI`: Complete shop interface implementation
+
+### Design Patterns
+- **Component System**: Modular building components
+- **Event-Driven UI**: UI events trigger business logic
+- **Resource Loading**: Automatic item discovery and loading
+- **State Management**: Centralized team and shop state
+
+This town system provides a solid foundation for a complete RPG town experience that can be easily extended and customized for your specific game needs.

+ 3 - 3
UserSettings/EditorUserSettings.asset

@@ -24,13 +24,13 @@ EditorUserSettings:
       value: 51020c5550545a0354575e7b47270744174e4b787e2b77687b7e1b37e7e4366d
       flags: 0
     RecentlyUsedSceneGuid-5:
-      value: 5a090503000558580f0d557342700844144f4d7c7b7d74692c281e63b0e2623c
+      value: 510500025d560a0c095d092111730d44464f4b78757b72357a701c31b7b16368
       flags: 0
     RecentlyUsedSceneGuid-6:
-      value: 510500025d560a0c095d092111730d44464f4b78757b72357a701c31b7b16368
+      value: 54030700010708095d0d5b7643260c44464f1e29797022342c2a1b67b1b03760
       flags: 0
     RecentlyUsedSceneGuid-7:
-      value: 54030700010708095d0d5b7643260c44464f1e29797022342c2a1b67b1b03760
+      value: 5a090503000558580f0d557342700844144f4d7c7b7d74692c281e63b0e2623c
       flags: 0
     vcSharedLogLevel:
       value: 0d5e400f0650

+ 31 - 31
UserSettings/Layouts/default-6000.dwlt

@@ -74,7 +74,7 @@ MonoBehaviour:
   m_MinSize: {x: 200, y: 50}
   m_MaxSize: {x: 16192, y: 8096}
   vertical: 0
-  controlID: 130
+  controlID: 125
   draggingID: 0
 --- !u!114 &4
 MonoBehaviour:
@@ -91,9 +91,9 @@ MonoBehaviour:
   m_Children: []
   m_Position:
     serializedVersion: 2
-    x: 1391
+    x: 924
     y: 0
-    width: 1374
+    width: 1841
     height: 854
   m_MinSize: {x: 52, y: 76}
   m_MaxSize: {x: 4002, y: 4026}
@@ -198,7 +198,7 @@ MonoBehaviour:
   m_MinSize: {x: 400, y: 100}
   m_MaxSize: {x: 32384, y: 16192}
   vertical: 0
-  controlID: 166
+  controlID: 161
   draggingID: 0
 --- !u!114 &9
 MonoBehaviour:
@@ -296,7 +296,7 @@ MonoBehaviour:
     serializedVersion: 2
     x: 633
     y: 0
-    width: 758
+    width: 291
     height: 854
   m_MinSize: {x: 202, y: 226}
   m_MaxSize: {x: 4002, y: 4026}
@@ -416,9 +416,9 @@ MonoBehaviour:
     m_TextWithWhitespace: "Game\u200B"
   m_Pos:
     serializedVersion: 2
-    x: 1392
+    x: 925
     y: 24
-    width: 1372
+    width: 1839
     height: 828
   m_SerializedDataModeController:
     m_DataMode: 0
@@ -437,7 +437,7 @@ MonoBehaviour:
   m_ShowGizmos: 0
   m_TargetDisplay: 0
   m_ClearColor: {r: 0, g: 0, b: 0, a: 0}
-  m_TargetSize: {x: 1372, y: 807}
+  m_TargetSize: {x: 1839, y: 807}
   m_TextureFilterMode: 0
   m_TextureHideFlags: 61
   m_RenderIMGUI: 1
@@ -452,8 +452,8 @@ MonoBehaviour:
     m_VRangeLocked: 0
     hZoomLockedByDefault: 0
     vZoomLockedByDefault: 0
-    m_HBaseRangeMin: -686
-    m_HBaseRangeMax: 686
+    m_HBaseRangeMin: -919.5
+    m_HBaseRangeMax: 919.5
     m_VBaseRangeMin: -403.5
     m_VBaseRangeMax: 403.5
     m_HAllowExceedBaseRangeMin: 1
@@ -473,23 +473,23 @@ MonoBehaviour:
       serializedVersion: 2
       x: 0
       y: 21
-      width: 1372
+      width: 1839
       height: 807
     m_Scale: {x: 1, y: 1}
-    m_Translation: {x: 686, y: 403.5}
+    m_Translation: {x: 919.5, y: 403.5}
     m_MarginLeft: 0
     m_MarginRight: 0
     m_MarginTop: 0
     m_MarginBottom: 0
     m_LastShownAreaInsideMargins:
       serializedVersion: 2
-      x: -686
+      x: -919.5
       y: -403.5
-      width: 1372
+      width: 1839
       height: 807
     m_MinimalGUI: 1
   m_defaultScale: 1
-  m_LastWindowPixelSize: {x: 1372, y: 828}
+  m_LastWindowPixelSize: {x: 1839, y: 828}
   m_ClearInEditMode: 1
   m_NoCameraWarning: 1
   m_LowResolutionForAspectRatios: 01000000000000000000
@@ -534,7 +534,7 @@ MonoBehaviour:
     m_OverlaysVisible: 1
   m_LockTracker:
     m_IsLocked: 0
-  m_LastSelectedObjectID: 50526
+  m_LastSelectedObjectID: -37720
 --- !u!114 &18
 MonoBehaviour:
   m_ObjectHideFlags: 52
@@ -576,7 +576,7 @@ MonoBehaviour:
       scrollPos: {x: 0, y: 0}
       m_SelectedIDs: 
       m_LastClickedID: 0
-      m_ExpandedIDs: 9e09efff9612effffa13efff1cf6ffff1afbfffff4ffffff
+      m_ExpandedIDs: 466dffff8ca8ffff50c6ffff12cdffff8ed2ffff72daffff80f2ffff16f3ffff1ef4ffffc0f4ffff68f5ffff08f6ffff1afbffff
       m_RenameOverlay:
         m_UserAcceptedRename: 0
         m_Name: 
@@ -624,7 +624,7 @@ MonoBehaviour:
     serializedVersion: 2
     x: 634
     y: 24
-    width: 756
+    width: 289
     height: 828
   m_SerializedDataModeController:
     m_DataMode: 0
@@ -1208,9 +1208,9 @@ MonoBehaviour:
   m_AudioPlay: 0
   m_DebugDrawModesUseInteractiveLightBakingData: 0
   m_Position:
-    m_Target: {x: 8.00217, y: 0.8804817, z: 1.8643875}
+    m_Target: {x: 0, y: 0, z: 0}
     speed: 2
-    m_Value: {x: 8.00217, y: 0.8804817, z: 1.8643875}
+    m_Value: {x: 0, y: 0, z: 0}
   m_RenderMode: 0
   m_CameraMode:
     drawMode: 0
@@ -1260,9 +1260,9 @@ MonoBehaviour:
     speed: 2
     m_Value: {x: 0.15735283, y: 0.6030923, z: -0.12288106, w: 0.7722813}
   m_Size:
-    m_Target: 1.9450212
+    m_Target: 10
     speed: 2
-    m_Value: 1.9450212
+    m_Value: 10
   m_Ortho:
     m_Target: 0
     speed: 2
@@ -1402,7 +1402,7 @@ MonoBehaviour:
     m_ContainerData: []
     m_OverlaysVisible: 1
   m_SearchFilter:
-    m_NameFilter: 
+    m_NameFilter: settlementinte
     m_ClassNames: []
     m_AssetLabels: []
     m_AssetBundleNames: []
@@ -1412,26 +1412,26 @@ MonoBehaviour:
     m_SkipHidden: 0
     m_SearchArea: 1
     m_Folders:
-    - Assets/Scenes
+    - Assets/Scripts/Objects
     m_Globs: []
     m_ProductIds: 
     m_AnyWithAssetOrigin: 0
-    m_OriginalText: 
+    m_OriginalText: settlementinte
     m_ImportLogFlags: 0
     m_FilterByTypeIntersection: 0
   m_ViewMode: 1
   m_StartGridSize: 67
   m_LastFolders:
-  - Assets/Scenes
+  - Assets/Scripts/Objects
   m_LastFoldersGridSize: 67
   m_LastProjectPath: C:\Users\Axel-PC\RPG-RougeLiteBatteler
   m_LockTracker:
     m_IsLocked: 0
   m_FolderTreeState:
-    scrollPos: {x: 0, y: 0}
-    m_SelectedIDs: 2ab70000
-    m_LastClickedID: 46890
-    m_ExpandedIDs: 00000000d2b40000d4b40000
+    scrollPos: {x: 0, y: 163}
+    m_SelectedIDs: 4ab70000
+    m_LastClickedID: 46922
+    m_ExpandedIDs: 0000000076b4000078b400007ab400007cb400007eb40000
     m_RenameOverlay:
       m_UserAcceptedRename: 0
       m_Name: 
@@ -1460,7 +1460,7 @@ MonoBehaviour:
     scrollPos: {x: 0, y: 0}
     m_SelectedIDs: 
     m_LastClickedID: 0
-    m_ExpandedIDs: 00000000d2b40000d4b40000
+    m_ExpandedIDs: 0000000076b4000078b400007ab400007cb400007eb40000
     m_RenameOverlay:
       m_UserAcceptedRename: 0
       m_Name: