86 lines
2.8 KiB
C#
86 lines
2.8 KiB
C#
using UnityEngine;
|
|
|
|
public class FurnitureObject : MonoBehaviour
|
|
{
|
|
[Header("Настройки")]
|
|
public LayerMask obstacleLayers;
|
|
|
|
private int _obstaclesCount = 0;
|
|
public bool IsPlacementValid => _obstaclesCount == 0;
|
|
|
|
// Переменные для нашей "коробки"
|
|
private GameObject _highlightBox;
|
|
private Material _highlightMaterial;
|
|
|
|
void Awake()
|
|
{
|
|
CreateHighlightBox();
|
|
}
|
|
|
|
private void CreateHighlightBox()
|
|
{
|
|
BoxCollider col = GetComponent<BoxCollider>();
|
|
if (col == null)
|
|
{
|
|
Debug.LogError("На префабе мебели нет BoxCollider! Коробка не появится.");
|
|
return;
|
|
}
|
|
|
|
// 1. Создаем обычный куб
|
|
_highlightBox = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
|
|
|
// 2. Удаляем с него коллайдер, чтобы он не мешал физике
|
|
Destroy(_highlightBox.GetComponent<Collider>());
|
|
|
|
// 3. Делаем куб дочерним к мебели и задаем размеры коллайдера
|
|
_highlightBox.transform.SetParent(transform);
|
|
_highlightBox.transform.localPosition = col.center;
|
|
_highlightBox.transform.localRotation = Quaternion.identity;
|
|
_highlightBox.transform.localScale = col.size;
|
|
|
|
// 4. Магия: Создаем прозрачный материал через код.
|
|
// Шейдер "Sprites/Default" есть в Unity всегда, он светится в темноте и поддерживает прозрачность.
|
|
_highlightMaterial = new Material(Shader.Find("Sprites/Default"));
|
|
_highlightBox.GetComponent<Renderer>().material = _highlightMaterial;
|
|
|
|
// Выключаем куб при старте
|
|
_highlightBox.SetActive(false);
|
|
}
|
|
|
|
public void SetEditMode(bool active)
|
|
{
|
|
if (_highlightBox != null)
|
|
{
|
|
_highlightBox.SetActive(active);
|
|
if (active) UpdateColor();
|
|
}
|
|
}
|
|
|
|
private void OnTriggerEnter(Collider other)
|
|
{
|
|
if (((1 << other.gameObject.layer) & obstacleLayers) != 0)
|
|
{
|
|
_obstaclesCount++;
|
|
UpdateColor();
|
|
}
|
|
}
|
|
|
|
private void OnTriggerExit(Collider other)
|
|
{
|
|
if (((1 << other.gameObject.layer) & obstacleLayers) != 0)
|
|
{
|
|
_obstaclesCount--;
|
|
UpdateColor();
|
|
}
|
|
}
|
|
|
|
private void UpdateColor()
|
|
{
|
|
if (_highlightMaterial != null)
|
|
{
|
|
// Зеленый или красный цвет (0.4f - это степень прозрачности)
|
|
Color targetColor = IsPlacementValid ? new Color(0, 1, 0, 0.4f) : new Color(1, 0, 0, 0.4f);
|
|
_highlightMaterial.color = targetColor;
|
|
}
|
|
}
|
|
} |