авто добавления кропаля на коллайдерах. Авто поиск всех элементов мебели. Полный газик
This commit is contained in:
1 parent
772fd3d7f6
commit
eff9613938
34 files changed
+2036
-98
No files matched your search
@@ -22,4 +22,6 @@ public class FurnitureItemSO : ScriptableObject
|
||||
public AssetReference prefabRef;
|
||||
|
||||
public List<FurniturePreset> availablePresets;
|
||||
[Header("Механика установки")]
|
||||
public bool isWallObject = false;
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.AddressableAssets;
|
||||
using UnityEngine.ResourceManagement.AsyncOperations;
|
||||
|
||||
public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
public enum EditTool { Move, Rotate }
|
||||
|
||||
[Header("Настройки")]
|
||||
public GameObject currentPrefab;
|
||||
public FurnitureItemSO currentItemData; // Заменили GameObject на SO
|
||||
public LayerMask floorLayer;
|
||||
public LayerMask wallLayer;
|
||||
public LayerMask furnitureLayer;
|
||||
@@ -19,7 +21,7 @@ public class FurnitureController : MonoBehaviour
|
||||
public float rotationSpeed = 5f;
|
||||
|
||||
[Header("Настройки двойного клика")]
|
||||
public float doubleClickThreshold = 0.3f; // Максимальное время между кликами в секундах
|
||||
public float doubleClickThreshold = 0.3f;
|
||||
|
||||
[Header("Связь с камерой")]
|
||||
public MonoBehaviour cameraController;
|
||||
@@ -33,7 +35,7 @@ public class FurnitureController : MonoBehaviour
|
||||
private Vector3 _lastInputPos;
|
||||
private Vector3 _dragOffset;
|
||||
|
||||
private float _lastClickTime = 0f; // Хранит время последнего клика
|
||||
private float _lastClickTime = 0f;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
@@ -41,7 +43,7 @@ public class FurnitureController : MonoBehaviour
|
||||
if (cameraController == null && _cam != null)
|
||||
cameraController = _cam.GetComponent("CameraController") as MonoBehaviour;
|
||||
|
||||
currentPrefab = null;
|
||||
currentItemData = null;
|
||||
editPanel.SetActive(false);
|
||||
if (rotate90Button != null) rotate90Button.SetActive(false);
|
||||
}
|
||||
@@ -52,26 +54,23 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
HandleEditing();
|
||||
}
|
||||
else if (currentPrefab != null)
|
||||
else if (currentItemData != null)
|
||||
{
|
||||
// Оставляем одинарный клик для установки НОВОЙ мебели
|
||||
if (Input.GetMouseButtonDown(0) && !shopPanel.activeSelf && !IsPointerOverUI())
|
||||
TryPlaceFurniture();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Логика двойного клика для выбора УЖЕ УСТАНОВЛЕННОЙ мебели
|
||||
if (Input.GetMouseButtonDown(0) && !shopPanel.activeSelf && !IsPointerOverUI())
|
||||
{
|
||||
float timeSinceLastClick = Time.time - _lastClickTime;
|
||||
|
||||
if (timeSinceLastClick <= doubleClickThreshold)
|
||||
{
|
||||
// Если время между кликами меньше порога — это двойной клик
|
||||
TrySelectPlacedFurniture();
|
||||
}
|
||||
|
||||
_lastClickTime = Time.time; // Запоминаем время текущего клика
|
||||
_lastClickTime = Time.time;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -99,7 +98,6 @@ public class FurnitureController : MonoBehaviour
|
||||
|
||||
if (foundFurniture)
|
||||
{
|
||||
// Для пола считаем смещение, настенные предметы просто цепляем к курсору
|
||||
if (!_activeFurnitureScript.isWallObject && Physics.Raycast(ray, out RaycastHit floorHit, 100f, floorLayer))
|
||||
{
|
||||
_dragOffset = _activeFurniture.transform.position - floorHit.point;
|
||||
@@ -122,17 +120,14 @@ public class FurnitureController : MonoBehaviour
|
||||
|
||||
if (_currentTool == EditTool.Move)
|
||||
{
|
||||
// === ЛОГИКА ДЛЯ НАСТЕННЫХ ПРЕДМЕТОВ ===
|
||||
if (_activeFurnitureScript.isWallObject)
|
||||
{
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, wallLayer))
|
||||
{
|
||||
_activeFurniture.transform.position = hit.point;
|
||||
// Магия: Поворачиваем объект "лицом" от стены
|
||||
_activeFurniture.transform.rotation = Quaternion.LookRotation(hit.normal);
|
||||
}
|
||||
}
|
||||
// === ЛОГИКА ДЛЯ НАПОЛЬНЫХ ПРЕДМЕТОВ (Старая) ===
|
||||
else
|
||||
{
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, floorLayer))
|
||||
@@ -180,7 +175,6 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
float deltaX = Input.mousePosition.x - _lastInputPos.x;
|
||||
|
||||
// Настенные предметы крутим вокруг своей оси Z (по циферблату), а напольные - вокруг мировой Y
|
||||
if (_activeFurnitureScript.isWallObject)
|
||||
_activeFurniture.transform.Rotate(Vector3.forward, -deltaX * rotationSpeed * 0.2f, Space.Self);
|
||||
else
|
||||
@@ -258,30 +252,51 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
|
||||
|
||||
// Определяем, куда пускать луч при установке в зависимости от типа предмета
|
||||
FurnitureObject prefabScript = currentPrefab.GetComponent<FurnitureObject>();
|
||||
LayerMask targetLayer = prefabScript.isWallObject ? wallLayer : floorLayer;
|
||||
// Берем слой для первичной установки из карточки товара SO!
|
||||
LayerMask targetLayer = currentItemData.isWallObject ? wallLayer : floorLayer;
|
||||
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, 100f, targetLayer))
|
||||
{
|
||||
_activeFurniture = Instantiate(currentPrefab, hit.point, Quaternion.identity);
|
||||
|
||||
// Если это стена - сразу поворачиваем спиной к ней
|
||||
if (prefabScript.isWallObject)
|
||||
// Блокируем новые клики, пока грузится ассет
|
||||
_isInteracting = true;
|
||||
|
||||
Quaternion spawnRot = Quaternion.identity;
|
||||
if (currentItemData.isWallObject)
|
||||
spawnRot = Quaternion.LookRotation(hit.normal);
|
||||
|
||||
// Запускаем асинхронную загрузку из Addressables
|
||||
currentItemData.prefabRef.InstantiateAsync(hit.point, spawnRot).Completed += handle =>
|
||||
{
|
||||
_activeFurniture.transform.rotation = Quaternion.LookRotation(hit.normal);
|
||||
}
|
||||
if (handle.Status == AsyncOperationStatus.Succeeded)
|
||||
{
|
||||
_activeFurniture = handle.Result;
|
||||
_activeFurnitureScript = _activeFurniture.GetComponent<FurnitureObject>();
|
||||
|
||||
// --- МАГИЯ АРХИТЕКТУРЫ ---
|
||||
// Находим скрипт визуала и применяем базовый цвет (Preset 0)
|
||||
FurnitureVisuals visuals = _activeFurniture.GetComponent<FurnitureVisuals>();
|
||||
if (visuals != null && currentItemData.availablePresets != null && currentItemData.availablePresets.Count > 0)
|
||||
{
|
||||
visuals.ApplyPreset(currentItemData.availablePresets[0]);
|
||||
}
|
||||
// -------------------------
|
||||
|
||||
_activeFurnitureScript = _activeFurniture.GetComponent<FurnitureObject>();
|
||||
_activeFurnitureScript.SetEditMode(true);
|
||||
|
||||
_currentTool = EditTool.Move;
|
||||
if (rotate90Button != null) rotate90Button.SetActive(false);
|
||||
_activeFurnitureScript.SetEditMode(true);
|
||||
|
||||
_currentTool = EditTool.Move;
|
||||
if (rotate90Button != null) rotate90Button.SetActive(false);
|
||||
|
||||
currentPrefab = null;
|
||||
_isInteracting = false;
|
||||
LockCamera(false);
|
||||
UpdateUIPosition();
|
||||
currentItemData = null; // Сбрасываем карточку из буфера
|
||||
_isInteracting = false;
|
||||
LockCamera(false);
|
||||
UpdateUIPosition();
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError($"Не удалось загрузить {currentItemData.itemName}. Проверьте галочку Addressables на префабе!");
|
||||
_isInteracting = false;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,7 +306,6 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
if (_activeFurnitureScript.isWallObject)
|
||||
{
|
||||
// Настенные объекты поворачиваем по их локальной оси Z (как часы)
|
||||
_activeFurniture.transform.Rotate(0, 0, 90f, Space.Self);
|
||||
}
|
||||
else
|
||||
@@ -322,7 +336,9 @@ public class FurnitureController : MonoBehaviour
|
||||
{
|
||||
if (_activeFurniture != null)
|
||||
{
|
||||
Destroy(_activeFurniture);
|
||||
// ПРАВИЛЬНОЕ удаление объекта, заспавненного через Addressables
|
||||
Addressables.ReleaseInstance(_activeFurniture);
|
||||
|
||||
_activeFurniture = null;
|
||||
_activeFurnitureScript = null;
|
||||
editPanel.SetActive(false);
|
||||
@@ -330,9 +346,10 @@ public class FurnitureController : MonoBehaviour
|
||||
}
|
||||
}
|
||||
|
||||
public void SelectFurnitureAndCloseShop(GameObject prefabToSelect)
|
||||
// Эта функция вызывается из ShopManager
|
||||
public void SelectFurnitureAndCloseShop(FurnitureItemSO itemToSelect)
|
||||
{
|
||||
currentPrefab = prefabToSelect;
|
||||
currentItemData = itemToSelect;
|
||||
shopPanel.SetActive(false);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,12 +2,9 @@ using UnityEngine;
|
||||
|
||||
public class FurnitureObject : MonoBehaviour
|
||||
{
|
||||
[Header("Тип объекта")]
|
||||
public bool isWallObject = false; // ГАЛОЧКА: Это настенный предмет?
|
||||
|
||||
[Header("Настройки")]
|
||||
public LayerMask obstacleLayers;
|
||||
|
||||
public bool isWallObject;
|
||||
private int _obstaclesCount = 0;
|
||||
public bool IsPlacementValid => _obstaclesCount == 0;
|
||||
|
||||
|
||||
@@ -1,52 +1,99 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI; // Обязательно добавляем для работы с интерфейсом
|
||||
|
||||
// Этот класс - наша "карточка товара". Он хранит иконку и 3D-модель.
|
||||
[System.Serializable] // Позволяет отображать этот класс в инспекторе Unity
|
||||
public class FurnitureItem
|
||||
{
|
||||
public string itemName; // Название (просто для вашего удобства в инспекторе)
|
||||
public Sprite icon; // Иконка для магазина
|
||||
public GameObject prefab; // 3D-модель для установки
|
||||
}
|
||||
using UnityEngine.UI;
|
||||
|
||||
public class ShopManager : MonoBehaviour
|
||||
{
|
||||
[Header("Связи")]
|
||||
public FurnitureController builder; // Ссылка на ваш скрипт строительства
|
||||
public GameObject buttonTemplate; // Наш префаб кнопки магазина
|
||||
public Transform contentPanel; // Тот самый объект Content с Grid Layout Group
|
||||
[Tooltip("Ссылка на скрипт управления строительством")]
|
||||
public FurnitureController builder;
|
||||
|
||||
[Tooltip("Префаб UI-кнопки магазина")]
|
||||
public GameObject buttonTemplate;
|
||||
|
||||
[Tooltip("Объект Content, внутри которого лежит Grid Layout Group")]
|
||||
public Transform contentPanel;
|
||||
|
||||
[Header("Каталог мебели")]
|
||||
public List<FurnitureItem> items; // Список всей мебели в игре
|
||||
[Tooltip("Список всех карточек товаров (Scriptable Objects)")]
|
||||
public List<FurnitureItemSO> items;
|
||||
|
||||
void Start()
|
||||
private void Start()
|
||||
{
|
||||
// Как только игра запускается, генерируем магазин
|
||||
GenerateShop();
|
||||
}
|
||||
|
||||
void GenerateShop()
|
||||
public void GenerateShop()
|
||||
{
|
||||
// Проходимся по каждому предмету в нашем каталоге
|
||||
foreach (FurnitureItem item in items)
|
||||
// 1. Очищаем панель от старых кнопок (полезно при переключении категорий)
|
||||
foreach (Transform child in contentPanel)
|
||||
{
|
||||
// 1. Создаем копию шаблона кнопки внутри панели Content
|
||||
Destroy(child.gameObject);
|
||||
}
|
||||
|
||||
// 2. Проходимся по каждой карточке в нашем каталоге
|
||||
foreach (FurnitureItemSO item in items)
|
||||
{
|
||||
if (item == null) continue; // Защита от пустых слотов в инспекторе
|
||||
|
||||
// Создаем новую кнопку внутри contentPanel
|
||||
GameObject newButton = Instantiate(buttonTemplate, contentPanel);
|
||||
|
||||
// 2. Находим компонент Image на этой кнопке и меняем картинку на нашу иконку
|
||||
newButton.GetComponent<Image>().sprite = item.icon;
|
||||
// Находим компонент Image на этой кнопке и применяем иконку из SO
|
||||
Image btnImage = newButton.GetComponent<Image>();
|
||||
if (btnImage != null && item.catalogIcon != null)
|
||||
{
|
||||
btnImage.sprite = item.catalogIcon;
|
||||
}
|
||||
|
||||
// 3. Находим компонент Button, чтобы настроить клик
|
||||
// Настраиваем действие при нажатии на кнопку
|
||||
Button btn = newButton.GetComponent<Button>();
|
||||
|
||||
// Сохраняем префаб в локальную переменную (это важно для правильной работы кода)
|
||||
GameObject prefabToSelect = item.prefab;
|
||||
|
||||
// 4. Программно добавляем действие при клике (то же самое, что плюсик в инспекторе)
|
||||
// Мы вызываем метод из вашего прошлого скрипта!
|
||||
btn.onClick.AddListener(() => builder.SelectFurnitureAndCloseShop(prefabToSelect));
|
||||
if (btn != null)
|
||||
{
|
||||
// Важно: создаем локальную переменную для передачи в событие (замыкание)
|
||||
FurnitureItemSO itemToSelect = item;
|
||||
|
||||
// При клике передаем нашу карточку товара прямо в контроллер строительства
|
||||
btn.onClick.AddListener(() =>
|
||||
{
|
||||
builder.SelectFurnitureAndCloseShop(itemToSelect);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// ==========================================
|
||||
// МАГИЯ ДЛЯ АВТО-ЗАПОЛНЕНИЯ СПИСКА
|
||||
// ==========================================
|
||||
|
||||
// Этот атрибут создает кнопку в контекстном меню скрипта
|
||||
[ContextMenu("Найти всю мебель в проекте")]
|
||||
private void FindAllFurnitureInProject()
|
||||
{
|
||||
// Этот код выполняется ТОЛЬКО в редакторе Unity, в саму игру на телефон он не попадет
|
||||
#if UNITY_EDITOR
|
||||
// 1. Очищаем старый список
|
||||
items.Clear();
|
||||
|
||||
// 2. Ищем ВСЕ файлы типа FurnitureItemSO во всех папках проекта
|
||||
string[] guids = UnityEditor.AssetDatabase.FindAssets("t:FurnitureItemSO");
|
||||
|
||||
foreach (string guid in guids)
|
||||
{
|
||||
// Узнаем путь к файлу
|
||||
string path = UnityEditor.AssetDatabase.GUIDToAssetPath(guid);
|
||||
|
||||
// Загружаем файл и добавляем в список
|
||||
FurnitureItemSO item = UnityEditor.AssetDatabase.LoadAssetAtPath<FurnitureItemSO>(path);
|
||||
if (item != null)
|
||||
{
|
||||
items.Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Говорим Unity сохранить изменения в скрипте (чтобы список не сбросился)
|
||||
UnityEditor.EditorUtility.SetDirty(this);
|
||||
|
||||
Debug.Log($"<color=green>Автоматически найдено и добавлено предметов: {items.Count}</color>");
|
||||
#endif
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user