2026-08-07 22:55:13 +03:00
using UnityEngine ;
2026-08-09 16:21:30 +03:00
[ExecuteAlways]
2026-08-07 22:55:13 +03:00
[RequireComponent(typeof(MeshRenderer))]
public class FurnitureVisuals : MonoBehaviour
{
private MeshRenderer _meshRenderer ;
private MaterialPropertyBlock _mpb ;
2026-08-09 16:21:30 +03:00
// Кэшируем новые ID для производительности
2026-08-07 22:55:13 +03:00
private static readonly int AtlasRectProp = Shader . PropertyToID ( "_AtlasRect" );
2026-08-09 16:21:30 +03:00
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 ;
2026-08-07 22:55:13 +03:00
private void Awake ()
{
_meshRenderer = GetComponent < MeshRenderer >();
_mpb = new MaterialPropertyBlock ();
}
2026-08-09 16:21:30 +03:00
private void Update ()
{
if (! Application . isPlaying && enableLivePreview && previewItem != null )
{
if ( previewItem . availablePresets . Count > 0 )
{
ApplyPreset ( previewItem . availablePresets [ 0 ]);
}
}
}
2026-08-07 22:55:13 +03:00
public void ApplyPreset ( FurniturePreset preset )
{
if ( preset == null || preset . slotStyles == null ) return ;
2026-08-09 16:21:30 +03:00
if ( _mpb == null ) _mpb = new MaterialPropertyBlock ();
if ( _meshRenderer == null ) _meshRenderer = GetComponent < MeshRenderer >();
2026-08-07 22:55:13 +03:00
for ( int i = 0 ; i < preset . slotStyles . Length ; i ++)
{
2026-08-09 16:21:30 +03:00
// --- НОВАЯ ЗАЩИТА ---
// Если индекс стиля больше, чем количество материалов на модели - пропускаем!
if ( i >= _meshRenderer . sharedMaterials . Length )
{
Debug . LogWarning ( $"[FurnitureVisuals] Пытаемся покрасить слот {i}, но на модели {_meshRenderer.gameObject.name} всего {_meshRenderer.sharedMaterials.Length} материалов. Лишние стили проигнорированы." );
continue ;
}
// ---------------------
2026-08-07 22:55:13 +03:00
AtlasStyleSO style = preset . slotStyles [ i ];
if ( style != null )
{
_meshRenderer . GetPropertyBlock ( _mpb , i );
_mpb . SetVector ( AtlasRectProp , style . atlasRect );
2026-08-09 16:21:30 +03:00
_mpb . SetFloat ( MetallicProp , style . metallic );
_mpb . SetFloat ( SmoothnessProp , style . smoothness );
2026-08-07 22:55:13 +03:00
2026-08-09 16:21:30 +03:00
Color finalEmissionColor = style . useEmission ? style . emissionColor : Color . black ;
_mpb . SetColor ( EmissionColorProp , finalEmissionColor );
2026-08-07 22:55:13 +03:00
_meshRenderer . SetPropertyBlock ( _mpb , i );
}
}
}
}