Добавил цвета из атлса, надо добавить иконки для них
This commit is contained in:
1 parent
2fd7b76285
commit
7f1386882d
126 files changed
+4802
-774
No files matched your search
@@ -5,7 +5,6 @@ using System.Collections.Generic;
|
||||
|
||||
public class FurnitureSOGenerator : EditorWindow
|
||||
{
|
||||
// Папка, куда скрипт будет складывать готовые SO
|
||||
private string savePath = "Assets/_Project/Data/Catalog/";
|
||||
|
||||
[MenuItem("Tools/Массовое создание Карточек (По префабам)")]
|
||||
@@ -32,20 +31,16 @@ public class FurnitureSOGenerator : EditorWindow
|
||||
{
|
||||
int count = 0;
|
||||
|
||||
// Создаем папку, если её вдруг нет
|
||||
System.IO.Directory.CreateDirectory(savePath);
|
||||
|
||||
foreach (GameObject obj in Selection.gameObjects)
|
||||
{
|
||||
// Проверяем, что выделили именно префаб из папки, а не объект со сцены
|
||||
if (PrefabUtility.GetPrefabAssetType(obj) == PrefabAssetType.Regular ||
|
||||
PrefabUtility.GetPrefabAssetType(obj) == PrefabAssetType.Model)
|
||||
{
|
||||
// 1. Создаем пустую карточку SO
|
||||
FurnitureItemSO newItem = ScriptableObject.CreateInstance<FurnitureItemSO>();
|
||||
newItem.itemName = obj.name; // Называем как префаб
|
||||
newItem.itemName = obj.name;
|
||||
|
||||
// 2. Ищем иконку (Sprite) с ТАКИМ ЖЕ именем, как у префаба
|
||||
string[] spriteGuids = AssetDatabase.FindAssets(obj.name + " t:Sprite");
|
||||
if (spriteGuids.Length > 0)
|
||||
{
|
||||
@@ -53,20 +48,22 @@ public class FurnitureSOGenerator : EditorWindow
|
||||
newItem.catalogIcon = AssetDatabase.LoadAssetAtPath<Sprite>(spritePath);
|
||||
}
|
||||
|
||||
// 3. Создаем асинхронную ссылку на префаб (Addressables)
|
||||
string prefabPath = AssetDatabase.GetAssetPath(obj);
|
||||
string prefabGuid = AssetDatabase.AssetPathToGUID(prefabPath);
|
||||
newItem.prefabRef = new AssetReference(prefabGuid);
|
||||
|
||||
// 4. Заботливо создаем 1 пустой пресет раскраски, чтобы вам не кликать "Плюсик" 26 раз
|
||||
newItem.availablePresets = new List<FurniturePreset>();
|
||||
FurniturePreset defaultPreset = new FurniturePreset();
|
||||
defaultPreset.presetName = "Базовый цвет";
|
||||
// Предполагаем, что у шкафа 1 слот материала. Если больше - вы поправите руками.
|
||||
defaultPreset.slotStyles = new AtlasStyleSO[1];
|
||||
newItem.availablePresets.Add(defaultPreset);
|
||||
// ==========================================
|
||||
// ИСПРАВЛЕННЫЙ БЛОК: НОВАЯ АРХИТЕКТУРА СЛОТОВ
|
||||
// ==========================================
|
||||
newItem.configurableSlots = new List<FurnitureSlotData>();
|
||||
|
||||
FurnitureSlotData defaultSlot = new FurnitureSlotData();
|
||||
defaultSlot.slotName = "Основная деталь";
|
||||
defaultSlot.availableStyles = new List<AtlasStyleSO>(); // Пустой список для стилей
|
||||
|
||||
newItem.configurableSlots.Add(defaultSlot);
|
||||
// ==========================================
|
||||
|
||||
// 5. Сохраняем SO файл в проект
|
||||
string soPath = savePath + obj.name + "_Data.asset";
|
||||
AssetDatabase.CreateAsset(newItem, soPath);
|
||||
|
||||
|
||||
@@ -2,26 +2,24 @@ using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.AddressableAssets;
|
||||
|
||||
// Вспомогательный класс для вариантов раскраски одного предмета
|
||||
// Новый класс: Описание одной детали мебели (например, "Подушки")
|
||||
[System.Serializable]
|
||||
public class FurniturePreset
|
||||
public class FurnitureSlotData
|
||||
{
|
||||
public string presetName;
|
||||
public Sprite presetIcon;
|
||||
[Tooltip("Массив стилей для слотов префаба. Если у стула 2 слота материалов, добавьте сюда 2 стиля.")]
|
||||
public AtlasStyleSO[] slotStyles;
|
||||
public string slotName; // Название для UI (например, "Каркас", "Матрас")
|
||||
public List<AtlasStyleSO> availableStyles; // Какие цвета доступны именно для этой детали
|
||||
}
|
||||
|
||||
[CreateAssetMenu(fileName = "NewFurnitureItem", menuName = "Furniture/Furniture Item")]
|
||||
public class FurnitureItemSO : ScriptableObject
|
||||
{
|
||||
public string itemName;
|
||||
public Sprite catalogIcon; // Иконка для общего каталога магазина
|
||||
|
||||
[Tooltip("Асинхронная ссылка на префаб мебели")]
|
||||
public Sprite catalogIcon;
|
||||
public AssetReference prefabRef;
|
||||
|
||||
public List<FurniturePreset> availablePresets;
|
||||
[Header("Механика установки")]
|
||||
public bool isWallObject = false;
|
||||
|
||||
// ВМЕСТО ПРЕСЕТОВ ТЕПЕРЬ СЛОТЫ:
|
||||
[Header("Настройка деталей (Слоты материалов)")]
|
||||
[Tooltip("Элемент 0 = Материал 0 (например, Каркас). Элемент 1 = Материал 1 (Подушки).")]
|
||||
public List<FurnitureSlotData> configurableSlots;
|
||||
}
|
||||
@@ -1,70 +1,92 @@
|
||||
using UnityEngine;
|
||||
|
||||
[ExecuteAlways]
|
||||
[ExecuteAlways] // Позволяет скрипту работать прямо в окне Scene без запуска игры
|
||||
[RequireComponent(typeof(MeshRenderer))]
|
||||
public class FurnitureVisuals : MonoBehaviour
|
||||
{
|
||||
[Header("Live Preview (Только для настройки в редакторе)")]
|
||||
public bool enableLivePreview = false;
|
||||
public FurnitureItemSO previewItem; // Перетащите сюда карточку, чтобы раскрасить объект на сцене
|
||||
|
||||
private MeshRenderer _meshRenderer;
|
||||
private MaterialPropertyBlock _mpb;
|
||||
|
||||
// Кэшируем новые ID для производительности
|
||||
// Кэшируем параметры шейдера для максимальной производительности
|
||||
private static readonly int AtlasRectProp = Shader.PropertyToID("_AtlasRect");
|
||||
private static readonly int MetallicProp = Shader.PropertyToID("_Metallic");
|
||||
private static readonly int SmoothnessProp = Shader.PropertyToID("_Smoothness");
|
||||
private static readonly int EmissionColorProp = Shader.PropertyToID("_EmissionColor");
|
||||
|
||||
[Header("Live Preview")]
|
||||
public bool enableLivePreview = false;
|
||||
public FurnitureItemSO previewItem;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
_meshRenderer = GetComponent<MeshRenderer>();
|
||||
_mpb = new MaterialPropertyBlock();
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// ЛОГИКА ПРЕДПРОСМОТРА В РЕДАКТОРЕ
|
||||
// ==========================================
|
||||
private void Update()
|
||||
{
|
||||
// Выполняется каждый кадр ТОЛЬКО в редакторе, если стоит галочка и назначена карточка
|
||||
if (!Application.isPlaying && enableLivePreview && previewItem != null)
|
||||
{
|
||||
if (previewItem.availablePresets.Count > 0)
|
||||
{
|
||||
ApplyPreset(previewItem.availablePresets[0]);
|
||||
}
|
||||
ApplyDefaultColors(previewItem);
|
||||
}
|
||||
}
|
||||
|
||||
public void ApplyPreset(FurniturePreset preset)
|
||||
// ==========================================
|
||||
// ОСНОВНАЯ ЛОГИКА ОКРАШИВАНИЯ
|
||||
// ==========================================
|
||||
|
||||
// Красит только ОДНУ деталь (по индексу слота в MeshRenderer)
|
||||
public void ApplyStyleToSlot(int slotIndex, AtlasStyleSO style)
|
||||
{
|
||||
if (preset == null || preset.slotStyles == null) return;
|
||||
if (style == null) return;
|
||||
|
||||
if (_mpb == null) _mpb = new MaterialPropertyBlock();
|
||||
// Подстраховка для режима [ExecuteAlways], если Awake еще не успел сработать
|
||||
if (_mpb == null) _mpb = new MaterialPropertyBlock();
|
||||
if (_meshRenderer == null) _meshRenderer = GetComponent<MeshRenderer>();
|
||||
|
||||
for (int i = 0; i < preset.slotStyles.Length; i++)
|
||||
// Защита от ошибки out of bounds (если слотов меньше, чем мы просим покрасить)
|
||||
if (slotIndex < 0 || slotIndex >= _meshRenderer.sharedMaterials.Length)
|
||||
{
|
||||
// --- НОВАЯ ЗАЩИТА ---
|
||||
// Если индекс стиля больше, чем количество материалов на модели - пропускаем!
|
||||
if (i >= _meshRenderer.sharedMaterials.Length)
|
||||
{
|
||||
Debug.LogWarning($"[FurnitureVisuals] Пытаемся покрасить слот {i}, но на модели {_meshRenderer.gameObject.name} всего {_meshRenderer.sharedMaterials.Length} материалов. Лишние стили проигнорированы.");
|
||||
continue;
|
||||
}
|
||||
// ---------------------
|
||||
// В редакторе можно раскомментировать строку ниже для отладки, но для релиза оставляем тихо
|
||||
// Debug.LogWarning($"[FurnitureVisuals] Пытаемся покрасить слот {slotIndex}, но их всего {_meshRenderer.sharedMaterials.Length}");
|
||||
return;
|
||||
}
|
||||
|
||||
AtlasStyleSO style = preset.slotStyles[i];
|
||||
if (style != null)
|
||||
{
|
||||
_meshRenderer.GetPropertyBlock(_mpb, i);
|
||||
|
||||
_mpb.SetVector(AtlasRectProp, style.atlasRect);
|
||||
_mpb.SetFloat(MetallicProp, style.metallic);
|
||||
_mpb.SetFloat(SmoothnessProp, style.smoothness);
|
||||
|
||||
Color finalEmissionColor = style.useEmission ? style.emissionColor : Color.black;
|
||||
_mpb.SetColor(EmissionColorProp, finalEmissionColor);
|
||||
// Берем текущий блок, чтобы не затереть другие параметры
|
||||
_meshRenderer.GetPropertyBlock(_mpb, slotIndex);
|
||||
|
||||
// Передаем координаты в Атласе
|
||||
_mpb.SetVector(AtlasRectProp, style.atlasRect);
|
||||
|
||||
// Передаем физические свойства материала
|
||||
_mpb.SetFloat(MetallicProp, style.metallic);
|
||||
_mpb.SetFloat(SmoothnessProp, style.smoothness);
|
||||
|
||||
// Передаем свечение (если галочка не стоит, передаем черный цвет = нет свечения)
|
||||
Color finalEmissionColor = style.useEmission ? style.emissionColor : Color.black;
|
||||
_mpb.SetColor(EmissionColorProp, finalEmissionColor);
|
||||
|
||||
_meshRenderer.SetPropertyBlock(_mpb, i);
|
||||
// Применяем настройки ИМЕННО к этому слоту
|
||||
_meshRenderer.SetPropertyBlock(_mpb, slotIndex);
|
||||
}
|
||||
|
||||
// Вызывается при спавне (или в превью), чтобы мебель не была базового серого цвета
|
||||
public void ApplyDefaultColors(FurnitureItemSO itemData)
|
||||
{
|
||||
if (itemData == null || itemData.configurableSlots == null) return;
|
||||
|
||||
// Проходимся по всем слотам, описанным в карточке (Каркас, Матрас и т.д.)
|
||||
for (int i = 0; i < itemData.configurableSlots.Count; i++)
|
||||
{
|
||||
// Если для этой детали добавлен хотя бы один стиль цвета
|
||||
if (itemData.configurableSlots[i].availableStyles.Count > 0)
|
||||
{
|
||||
// Применяем САМЫЙ ПЕРВЫЙ стиль в списке
|
||||
ApplyStyleToSlot(i, itemData.configurableSlots[i].availableStyles[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,19 +8,19 @@ public class FurnitureController : MonoBehaviour
|
||||
public enum EditTool { Move, Rotate }
|
||||
|
||||
[Header("Настройки")]
|
||||
public FurnitureItemSO currentItemData; // Заменили GameObject на SO
|
||||
public FurnitureItemSO currentItemData;
|
||||
public LayerMask floorLayer;
|
||||
public LayerMask wallLayer;
|
||||
public LayerMask furnitureLayer;
|
||||
|
||||
[Header("Связь с UI")]
|
||||
[SerializeField] private GameObject shopPanel;
|
||||
|
||||
[Header("Режим редактирования (UI)")]
|
||||
[SerializeField] private GameObject editPanel;
|
||||
[SerializeField] private GameObject rotate90Button;
|
||||
public FurniturePaletteUI paletteUI; // Ссылка на скрипт палитры цветов
|
||||
|
||||
[Header("Настройки взаимодействия")]
|
||||
public float rotationSpeed = 5f;
|
||||
|
||||
[Header("Настройки двойного клика")]
|
||||
public float doubleClickThreshold = 0.3f;
|
||||
|
||||
[Header("Связь с камерой")]
|
||||
@@ -34,8 +34,6 @@ public class FurnitureController : MonoBehaviour
|
||||
private bool _isInteracting = false;
|
||||
private Vector3 _lastInputPos;
|
||||
private Vector3 _dragOffset;
|
||||
[Header("Связь с UI Цветов")]
|
||||
public FurniturePaletteUI paletteUI; // Ссылка на новый скрипт
|
||||
private float _lastClickTime = 0f;
|
||||
|
||||
private void Start()
|
||||
@@ -51,15 +49,18 @@ public class FurnitureController : MonoBehaviour
|
||||
|
||||
void Update()
|
||||
{
|
||||
// 1. Если мебель уже выбрана и находится в режиме редактирования
|
||||
if (_activeFurniture != null)
|
||||
{
|
||||
HandleEditing();
|
||||
}
|
||||
// 2. Если мы выбрали предмет в магазине и готовы его поставить
|
||||
else if (currentItemData != null)
|
||||
{
|
||||
if (Input.GetMouseButtonDown(0) && !shopPanel.activeSelf && !IsPointerOverUI())
|
||||
TryPlaceFurniture();
|
||||
}
|
||||
// 3. Режим ожидания: ловим двойной клик по УЖЕ стоящей мебели
|
||||
else
|
||||
{
|
||||
if (Input.GetMouseButtonDown(0) && !shopPanel.activeSelf && !IsPointerOverUI())
|
||||
@@ -133,9 +134,14 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, floorLayer))
|
||||
{
|
||||
// Вычисляем настоящий низ мебели
|
||||
Vector3 worldBottomOffset = _activeFurniture.transform.TransformVector(_activeFurnitureScript.bottomOffset);
|
||||
|
||||
Vector3 currentPos = _activeFurniture.transform.position;
|
||||
Vector3 targetPos = hit.point + _dragOffset;
|
||||
targetPos.y = currentPos.y;
|
||||
|
||||
// Жестко привязываем дно к полу
|
||||
targetPos.y = hit.point.y - worldBottomOffset.y;
|
||||
|
||||
Vector3 moveDir = targetPos - currentPos;
|
||||
float moveDist = moveDir.magnitude;
|
||||
@@ -167,7 +173,8 @@ public class FurnitureController : MonoBehaviour
|
||||
}
|
||||
}
|
||||
}
|
||||
targetPos.y = currentPos.y;
|
||||
|
||||
targetPos.y = hit.point.y - worldBottomOffset.y;
|
||||
_activeFurniture.transform.position = targetPos;
|
||||
}
|
||||
}
|
||||
@@ -176,10 +183,13 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
float deltaX = Input.mousePosition.x - _lastInputPos.x;
|
||||
|
||||
// Вращаем вокруг геометрического центра коллайдеров
|
||||
Vector3 worldCenter = _activeFurniture.transform.TransformPoint(_activeFurnitureScript.centerOffset);
|
||||
|
||||
if (_activeFurnitureScript.isWallObject)
|
||||
_activeFurniture.transform.Rotate(Vector3.forward, -deltaX * rotationSpeed * 0.2f, Space.Self);
|
||||
_activeFurniture.transform.RotateAround(worldCenter, _activeFurniture.transform.forward, -deltaX * rotationSpeed * 0.2f);
|
||||
else
|
||||
_activeFurniture.transform.Rotate(Vector3.up, -deltaX * rotationSpeed * 0.2f, Space.World);
|
||||
_activeFurniture.transform.RotateAround(worldCenter, Vector3.up, -deltaX * rotationSpeed * 0.2f);
|
||||
}
|
||||
|
||||
_lastInputPos = Input.mousePosition;
|
||||
@@ -204,7 +214,7 @@ public class FurnitureController : MonoBehaviour
|
||||
_currentTool = EditTool.Move;
|
||||
if (rotate90Button != null) rotate90Button.SetActive(false);
|
||||
|
||||
// Показываем панель цветов при выборе предмета
|
||||
// Показываем палитру цветов
|
||||
if (paletteUI != null) paletteUI.ShowColors(_activeFurnitureScript);
|
||||
|
||||
_isInteracting = false;
|
||||
@@ -256,19 +266,19 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
|
||||
// Берем слой для первичной установки из карточки товара SO!
|
||||
// Определяем, куда пускать луч (на стену или на пол)
|
||||
LayerMask targetLayer = currentItemData.isWallObject ? wallLayer : floorLayer;
|
||||
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, targetLayer))
|
||||
{
|
||||
// Блокируем новые клики, пока грузится ассет
|
||||
_isInteracting = true;
|
||||
_isInteracting = true; // Блокируем новые клики, пока идет асинхронная загрузка
|
||||
|
||||
// Считаем стартовый поворот (для стен - "лицом" от стены)
|
||||
Quaternion spawnRot = Quaternion.identity;
|
||||
if (currentItemData.isWallObject)
|
||||
spawnRot = Quaternion.LookRotation(hit.normal);
|
||||
|
||||
// Запускаем асинхронную загрузку из Addressables
|
||||
// Асинхронно загружаем префаб через Addressables
|
||||
currentItemData.prefabRef.InstantiateAsync(hit.point, spawnRot).Completed += handle =>
|
||||
{
|
||||
if (handle.Status == AsyncOperationStatus.Succeeded)
|
||||
@@ -276,33 +286,51 @@ public class FurnitureController : MonoBehaviour
|
||||
_activeFurniture = handle.Result;
|
||||
_activeFurnitureScript = _activeFurniture.GetComponent<FurnitureObject>();
|
||||
|
||||
// --- МАГИЯ АРХИТЕКТУРЫ ---
|
||||
// Инъекция карточки товара в объект на сцене!
|
||||
// ==========================================
|
||||
// 1. ИНЪЕКЦИЯ ДАННЫХ В ПРЕФАБ
|
||||
// ==========================================
|
||||
_activeFurnitureScript.runtimeItemData = currentItemData;
|
||||
|
||||
// ==========================================
|
||||
// 2. ПРИМЕНЕНИЕ ЦВЕТОВ (НОВАЯ АРХИТЕКТУРА)
|
||||
// ==========================================
|
||||
FurnitureVisuals visuals = _activeFurniture.GetComponent<FurnitureVisuals>();
|
||||
if (visuals != null && currentItemData.availablePresets != null && currentItemData.availablePresets.Count > 0)
|
||||
if (visuals != null)
|
||||
{
|
||||
visuals.ApplyPreset(currentItemData.availablePresets[0]);
|
||||
// Автоматически красим все детали первыми доступными цветами из списков
|
||||
visuals.ApplyDefaultColors(currentItemData);
|
||||
}
|
||||
|
||||
// Показываем панель цветов для только что заспавненного объекта
|
||||
// Открываем обновленную палитру с вкладками
|
||||
if (paletteUI != null) paletteUI.ShowColors(_activeFurnitureScript);
|
||||
// -------------------------
|
||||
|
||||
// ==========================================
|
||||
// 3. УМНЫЙ ПИВОТ (АВТО-ВЫРАВНИВАНИЕ)
|
||||
// ==========================================
|
||||
if (!currentItemData.isWallObject)
|
||||
{
|
||||
// Вычисляем, где находится математическое дно у модели с учетом ее поворота
|
||||
Vector3 worldBottomOffset = _activeFurniture.transform.TransformVector(_activeFurnitureScript.bottomOffset);
|
||||
|
||||
// Смещаем объект так, чтобы его дно оказалось ровно в точке клика на полу
|
||||
_activeFurniture.transform.position = hit.point - worldBottomOffset;
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 4. ПЕРЕХОД В РЕЖИМ РЕДАКТИРОВАНИЯ
|
||||
// ==========================================
|
||||
_activeFurnitureScript.SetEditMode(true);
|
||||
|
||||
_currentTool = EditTool.Move;
|
||||
if (rotate90Button != null) rotate90Button.SetActive(false);
|
||||
|
||||
currentItemData = null; // Сбрасываем карточку из буфера
|
||||
currentItemData = null; // Очищаем карточку из "буфера" контроллера
|
||||
_isInteracting = false;
|
||||
LockCamera(false);
|
||||
UpdateUIPosition();
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError($"Не удалось загрузить {currentItemData.itemName}. Проверьте галочку Addressables на префабе!");
|
||||
Debug.LogError($"Не удалось загрузить {currentItemData.itemName}. Проверьте галочку Addressable на префабе!");
|
||||
_isInteracting = false;
|
||||
}
|
||||
};
|
||||
@@ -313,15 +341,18 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
if (_activeFurniture != null)
|
||||
{
|
||||
Vector3 worldCenter = _activeFurniture.transform.TransformPoint(_activeFurnitureScript.centerOffset);
|
||||
|
||||
if (_activeFurnitureScript.isWallObject)
|
||||
{
|
||||
_activeFurniture.transform.Rotate(0, 0, 90f, Space.Self);
|
||||
_activeFurniture.transform.RotateAround(worldCenter, _activeFurniture.transform.forward, 90f);
|
||||
}
|
||||
else
|
||||
{
|
||||
float currentY = _activeFurniture.transform.eulerAngles.y;
|
||||
float snappedY = Mathf.Round(currentY / 90f) * 90f;
|
||||
_activeFurniture.transform.rotation = Quaternion.Euler(0, snappedY + 90f, 0);
|
||||
_activeFurniture.transform.RotateAround(worldCenter, Vector3.up, 90f);
|
||||
|
||||
Vector3 euler = _activeFurniture.transform.eulerAngles;
|
||||
_activeFurniture.transform.eulerAngles = new Vector3(euler.x, Mathf.Round(euler.y / 90f) * 90f, euler.z);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -336,8 +367,10 @@ public class FurnitureController : MonoBehaviour
|
||||
_activeFurnitureScript.SetEditMode(false);
|
||||
_activeFurniture = null;
|
||||
_activeFurnitureScript = null;
|
||||
|
||||
editPanel.SetActive(false);
|
||||
if (paletteUI != null) paletteUI.HideColors();
|
||||
if (paletteUI != null) paletteUI.HideColors(); // Прячем палитру
|
||||
|
||||
LockCamera(false);
|
||||
}
|
||||
}
|
||||
@@ -346,18 +379,18 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
if (_activeFurniture != null)
|
||||
{
|
||||
// ПРАВИЛЬНОЕ удаление объекта, заспавненного через Addressables
|
||||
Addressables.ReleaseInstance(_activeFurniture);
|
||||
|
||||
_activeFurniture = null;
|
||||
_activeFurnitureScript = null;
|
||||
|
||||
editPanel.SetActive(false);
|
||||
if (paletteUI != null) paletteUI.HideColors();
|
||||
if (paletteUI != null) paletteUI.HideColors(); // Прячем палитру
|
||||
|
||||
LockCamera(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Эта функция вызывается из ShopManager
|
||||
public void SelectFurnitureAndCloseShop(FurnitureItemSO itemToSelect)
|
||||
{
|
||||
currentItemData = itemToSelect;
|
||||
|
||||
@@ -2,45 +2,64 @@ using UnityEngine;
|
||||
|
||||
public class FurnitureObject : MonoBehaviour
|
||||
{
|
||||
[HideInInspector] public FurnitureItemSO runtimeItemData;
|
||||
|
||||
[Header("Тип объекта")]
|
||||
public bool isWallObject = false;
|
||||
|
||||
[Header("Настройки")]
|
||||
public LayerMask obstacleLayers;
|
||||
public bool isWallObject;
|
||||
|
||||
private int _obstaclesCount = 0;
|
||||
public bool IsPlacementValid => _obstaclesCount == 0;
|
||||
[HideInInspector] public FurnitureItemSO runtimeItemData;
|
||||
|
||||
private GameObject _highlightBox;
|
||||
private Material _highlightMaterial;
|
||||
|
||||
// --- НОВЫЕ ПЕРЕМЕННЫЕ ДЛЯ УМНОГО ПИВОТА ---
|
||||
[HideInInspector] public Vector3 bottomOffset;
|
||||
[HideInInspector] public Vector3 centerOffset;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
CalculateSmartPivot();
|
||||
CreateHighlightBox();
|
||||
}
|
||||
|
||||
private void CalculateSmartPivot()
|
||||
{
|
||||
BoxCollider[] colliders = GetComponents<BoxCollider>();
|
||||
if (colliders.Length == 0) return;
|
||||
|
||||
// Вычисляем общую коробку, охватывающую все коллайдеры
|
||||
Bounds totalBounds = new Bounds(colliders[0].center, colliders[0].size);
|
||||
for (int i = 1; i < colliders.Length; i++)
|
||||
{
|
||||
totalBounds.Encapsulate(new Bounds(colliders[i].center, colliders[i].size));
|
||||
}
|
||||
|
||||
// Локальный центр (для идеального вращения)
|
||||
centerOffset = totalBounds.center;
|
||||
|
||||
// Локальный низ (пол) - отнимаем половину высоты от центра
|
||||
bottomOffset = totalBounds.center;
|
||||
bottomOffset.y -= totalBounds.extents.y;
|
||||
}
|
||||
|
||||
private void CreateHighlightBox()
|
||||
{
|
||||
// Ищем ВСЕ коллайдеры на объекте
|
||||
BoxCollider[] colliders = GetComponents<BoxCollider>();
|
||||
if (colliders.Length == 0) return;
|
||||
|
||||
// Создаем "виртуальную коробку", которая охватит первый коллайдер
|
||||
Bounds totalBounds = new Bounds(colliders[0].center, colliders[0].size);
|
||||
|
||||
// Добавляем в эту коробку все остальные коллайдеры (для формы буквы Г)
|
||||
for (int i = 1; i < colliders.Length; i++)
|
||||
{
|
||||
Bounds b = new Bounds(colliders[i].center, colliders[i].size);
|
||||
totalBounds.Encapsulate(b);
|
||||
}
|
||||
for (int i = 1; i < colliders.Length; i++) totalBounds.Encapsulate(new Bounds(colliders[i].center, colliders[i].size));
|
||||
|
||||
_highlightBox = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
Destroy(_highlightBox.GetComponent<Collider>());
|
||||
|
||||
_highlightBox.transform.SetParent(transform);
|
||||
|
||||
// Ставим зеленую коробку в общий центр и задаем общий размер
|
||||
_highlightBox.transform.localPosition = totalBounds.center;
|
||||
_highlightBox.transform.localRotation = Quaternion.identity;
|
||||
// Умножаем на 1.02, чтобы зеленая коробка была чуть-чуть больше мебели (для красоты)
|
||||
_highlightBox.transform.localScale = totalBounds.size * 1.02f;
|
||||
|
||||
_highlightMaterial = new Material(Shader.Find("Sprites/Default"));
|
||||
|
||||
@@ -1,85 +1,139 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using TMPro;
|
||||
|
||||
public class FurniturePaletteUI : MonoBehaviour
|
||||
{
|
||||
[Header("UI Элементы")]
|
||||
public GameObject palettePanel; // Панель, которая выезжает с цветами
|
||||
public Transform contentContainer; // Объект с Horizontal/Grid Layout Group
|
||||
public GameObject colorBtnTemplate; // Префаб кнопки цвета
|
||||
[Header("UI Элементы: Палитра (Scroll View)")]
|
||||
public GameObject palettePanel;
|
||||
public Transform colorsContainer;
|
||||
public GameObject colorBtnTemplate;
|
||||
|
||||
[Header("UI Элементы: Вкладки деталей")]
|
||||
public GameObject tabsPanel;
|
||||
public Transform tabsContainer;
|
||||
public GameObject tabBtnTemplate;
|
||||
|
||||
private FurnitureObject _currentFurniture;
|
||||
private FurnitureVisuals _currentVisuals;
|
||||
private int _selectedSlotIndex = 0;
|
||||
|
||||
public void ShowColors(FurnitureObject furniture)
|
||||
{
|
||||
if (furniture == null || furniture.runtimeItemData == null) return;
|
||||
|
||||
_currentVisuals = furniture.GetComponent<FurnitureVisuals>();
|
||||
if (_currentVisuals == null || furniture.runtimeItemData.availablePresets.Count <= 1)
|
||||
if (_currentVisuals == null || furniture.runtimeItemData.configurableSlots.Count == 0)
|
||||
{
|
||||
HideColors();
|
||||
return;
|
||||
}
|
||||
|
||||
_currentFurniture = furniture;
|
||||
_selectedSlotIndex = 0;
|
||||
|
||||
GenerateTabs();
|
||||
ShowColorsForSlot(_selectedSlotIndex);
|
||||
|
||||
palettePanel.SetActive(true);
|
||||
tabsPanel.SetActive(furniture.runtimeItemData.configurableSlots.Count > 1);
|
||||
}
|
||||
|
||||
private void GenerateTabs()
|
||||
{
|
||||
foreach (Transform child in tabsContainer) Destroy(child.gameObject);
|
||||
|
||||
for (int i = 0; i < _currentFurniture.runtimeItemData.configurableSlots.Count; i++)
|
||||
{
|
||||
int slotIndex = i;
|
||||
string slotName = _currentFurniture.runtimeItemData.configurableSlots[i].slotName;
|
||||
|
||||
GameObject tabObj = Instantiate(tabBtnTemplate, tabsContainer, false);
|
||||
tabObj.transform.localScale = Vector3.one;
|
||||
|
||||
TextMeshProUGUI tabText = tabObj.GetComponentInChildren<TextMeshProUGUI>();
|
||||
if (tabText != null) tabText.text = slotName;
|
||||
|
||||
Button btn = tabObj.GetComponent<Button>();
|
||||
btn.onClick.AddListener(() =>
|
||||
{
|
||||
_selectedSlotIndex = slotIndex;
|
||||
ShowColorsForSlot(_selectedSlotIndex);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void ShowColorsForSlot(int slotIndex)
|
||||
{
|
||||
// 1. Очищаем старые кнопки
|
||||
foreach (Transform child in colorsContainer) Destroy(child.gameObject);
|
||||
|
||||
var slotData = _currentFurniture.runtimeItemData.configurableSlots[slotIndex];
|
||||
|
||||
// Если для этой детали нет цветов - скрываем панель и выходим
|
||||
if (slotData.availableStyles == null || slotData.availableStyles.Count == 0)
|
||||
{
|
||||
palettePanel.SetActive(false);
|
||||
return;
|
||||
return;
|
||||
}
|
||||
|
||||
palettePanel.SetActive(true);
|
||||
|
||||
foreach (Transform child in contentContainer)
|
||||
// 2. Создаем новые кнопки
|
||||
foreach (AtlasStyleSO style in slotData.availableStyles)
|
||||
{
|
||||
Destroy(child.gameObject);
|
||||
}
|
||||
if (style == null) continue;
|
||||
|
||||
foreach (FurniturePreset preset in furniture.runtimeItemData.availablePresets)
|
||||
{
|
||||
// ДОБАВЛЯЕМ false в конце! Это запретит кнопке улетать по оси Z
|
||||
GameObject btnObj = Instantiate(colorBtnTemplate, contentContainer, false);
|
||||
GameObject btnObj = Instantiate(colorBtnTemplate, colorsContainer, false);
|
||||
|
||||
RectTransform rect = btnObj.GetComponent<RectTransform>();
|
||||
rect.localScale = Vector3.one;
|
||||
// Принудительно обнуляем координату Z (на всякий случай)
|
||||
rect.localPosition = new Vector3(rect.localPosition.x, rect.localPosition.y, 0f);
|
||||
rect.sizeDelta = new Vector2(100f, 100f); // Ваш размер кнопки
|
||||
rect.sizeDelta = new Vector2(100f, 100f);
|
||||
|
||||
Image img = btnObj.GetComponent<Image>();
|
||||
if (img != null)
|
||||
{
|
||||
if (preset.presetIcon != null) img.sprite = preset.presetIcon;
|
||||
else if (preset.slotStyles != null && preset.slotStyles.Length > 0 && preset.slotStyles[0] != null)
|
||||
img.sprite = preset.slotStyles[0].uiIcon;
|
||||
|
||||
// Убеждаемся, что кнопка не прозрачная
|
||||
img.color = new Color(img.color.r, img.color.g, img.color.b, 1f);
|
||||
img.sprite = style.uiIcon;
|
||||
img.color = new Color(img.color.r, img.color.g, img.color.b, 1f);
|
||||
}
|
||||
|
||||
Button btn = btnObj.GetComponent<Button>();
|
||||
FurniturePreset presetToApply = preset;
|
||||
AtlasStyleSO styleToApply = style;
|
||||
|
||||
btn.onClick.AddListener(() =>
|
||||
{
|
||||
if (_currentVisuals != null) _currentVisuals.ApplyPreset(presetToApply);
|
||||
if (_currentVisuals != null) _currentVisuals.ApplyStyleToSlot(slotIndex, styleToApply);
|
||||
});
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// УМНЫЙ РАСЧЕТ РАЗМЕРА И ПРОКРУТКИ
|
||||
// ==========================================
|
||||
|
||||
// 1. Заставляем Content рассчитать свою ширину со всеми кнопками
|
||||
RectTransform contentRect = contentContainer.GetComponent<RectTransform>();
|
||||
LayoutRebuilder.ForceRebuildLayoutImmediate(contentRect);
|
||||
float totalButtonsWidth = contentRect.sizeDelta.x;
|
||||
// 3. Вызываем умный перерасчет размера панели
|
||||
ResizePalettePanel();
|
||||
}
|
||||
|
||||
// 2. Вычисляем максимальную ширину (например, 90% от ширины экрана/канваса)
|
||||
private void ResizePalettePanel()
|
||||
{
|
||||
// Заставляем Unity моментально пересчитать UI (решает баг с нулевым размером)
|
||||
Canvas.ForceUpdateCanvases();
|
||||
|
||||
RectTransform contentRect = colorsContainer.GetComponent<RectTransform>();
|
||||
LayoutRebuilder.ForceRebuildLayoutImmediate(contentRect);
|
||||
|
||||
// Узнаем, сколько места реально заняли все кнопки внутри Content
|
||||
float totalButtonsWidth = contentRect.rect.width;
|
||||
|
||||
// Вычисляем максимум (например, 90% от ширины экрана)
|
||||
RectTransform canvasRect = palettePanel.GetComponentInParent<Canvas>().GetComponent<RectTransform>();
|
||||
float maxAllowedWidth = canvasRect.rect.width * 0.9f;
|
||||
|
||||
// 3. Выбираем, что меньше: реальная ширина кнопок или максимальная ширина
|
||||
// Выбираем ширину: либо размер кнопок, либо максимум экрана
|
||||
float finalPanelWidth = Mathf.Min(totalButtonsWidth, maxAllowedWidth);
|
||||
|
||||
// 4. Применяем этот размер к ГЛАВНОЙ панели (Scroll View)
|
||||
// Меняем ширину Главной Панели (Scroll View)
|
||||
RectTransform panelRect = palettePanel.GetComponent<RectTransform>();
|
||||
panelRect.sizeDelta = new Vector2(finalPanelWidth, panelRect.sizeDelta.y);
|
||||
|
||||
// 5. Отключаем прокрутку, если кнопки влезли в экран (чтобы панель не "пружинила" без нужды)
|
||||
// Включаем прокрутку ТОЛЬКО если кнопки не влезли
|
||||
ScrollRect scroll = palettePanel.GetComponent<ScrollRect>();
|
||||
if (scroll != null)
|
||||
{
|
||||
@@ -90,6 +144,8 @@ public class FurniturePaletteUI : MonoBehaviour
|
||||
public void HideColors()
|
||||
{
|
||||
palettePanel.SetActive(false);
|
||||
tabsPanel.SetActive(false);
|
||||
_currentVisuals = null;
|
||||
_currentFurniture = null;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
using UnityEngine;
|
||||
|
||||
using UnityEngine;
|
||||
|
||||
|
||||
public class CameraFollow : MonoBehaviour
|
||||
{
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
|
||||
using UnityEngine;
|
||||
|
||||
// RandomLaneChangingBehavior.cs
|
||||
using UnityEngine;
|
||||
|
||||
public class RandomLaneChangingBehavior : ICarBehavior
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user