439 lines
14 KiB
C#
439 lines
14 KiB
C#
#nullable enable
|
|
using System;
|
|
using UnityEngine;
|
|
using UnityEngine.UIElements;
|
|
|
|
namespace UVC.UIToolkit
|
|
{
|
|
/// <summary>
|
|
/// Vector2(2D 벡터) 입력 필드 컴포넌트.
|
|
/// Unity Vector2Field를 래핑하여 커스텀 스타일을 적용합니다.
|
|
/// X, Y 두 개의 float 값을 입력받아 2D 좌표나 크기를 표현합니다.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para><b>Vector2란?</b></para>
|
|
/// <para>Vector2는 2차원 공간의 점이나 방향을 나타내는 구조체입니다.</para>
|
|
/// <para>- X: 수평(가로) 방향의 값</para>
|
|
/// <para>- Y: 수직(세로) 방향의 값</para>
|
|
/// <para>주로 2D 게임의 위치, UI 크기, 텍스처 좌표(UV) 등에 사용됩니다.</para>
|
|
/// <para><b>주요 기능:</b></para>
|
|
/// <list type="bullet">
|
|
/// <item><description>X, Y 축 라벨 커스터마이징</description></item>
|
|
/// <item><description>읽기 전용 모드</description></item>
|
|
/// <item><description>Validation 함수를 통한 입력 검증 (FocusOut 시 자동 호출)</description></item>
|
|
/// <item><description>에러 상태 시 붉은 외곽선 + 에러 메시지 표시</description></item>
|
|
/// </list>
|
|
/// </remarks>
|
|
/// <example>
|
|
/// <para><b>C# 코드에서 사용:</b></para>
|
|
/// <code>
|
|
/// // 기본 Vector2 필드 생성
|
|
/// var vec2Field = new UTKVector2Field();
|
|
/// vec2Field.label = "UI 크기";
|
|
///
|
|
/// // 초기값 설정
|
|
/// vec2Field.Value = new Vector2(100, 50); // 가로 100, 세로 50
|
|
///
|
|
/// // 값 변경 이벤트 처리
|
|
/// vec2Field.OnValueChanged += (vec) => {
|
|
/// Debug.Log($"크기 변경: 가로={vec.x}, 세로={vec.y}");
|
|
/// };
|
|
///
|
|
/// // 라벨 커스터마이징
|
|
/// vec2Field.XLabel = "가로";
|
|
/// vec2Field.YLabel = "세로";
|
|
///
|
|
/// // 비활성화
|
|
/// vec2Field.IsEnabled = false;
|
|
///
|
|
/// // 읽기 전용 (사용자가 수정할 수 없음)
|
|
/// var readOnlyField = new UTKVector2Field("고정 크기");
|
|
/// readOnlyField.Value = new Vector2(100, 50);
|
|
/// readOnlyField.IsReadOnly = true;
|
|
/// </code>
|
|
/// <para><b>Validation (입력 검증):</b></para>
|
|
/// <code>
|
|
/// // 검증 함수 설정 (Func<bool>)
|
|
/// var sizeField = new UTKVector2Field("크기");
|
|
/// sizeField.ErrorMessage = "크기는 양수여야 합니다.";
|
|
/// sizeField.Validation = () => sizeField.Value.x > 0 && sizeField.Value.y > 0;
|
|
/// // → FocusOut 시 자동으로 검증
|
|
/// // → 실패 시 붉은 외곽선 + 에러 메시지 표시, 통과 시 자동 해제
|
|
///
|
|
/// // 강제 검증 호출 (예: 폼 제출 버튼 클릭 시)
|
|
/// bool isValid = sizeField.Validate();
|
|
/// if (!isValid) return; // 검증 실패
|
|
///
|
|
/// // 에러 수동 해제
|
|
/// sizeField.ClearError();
|
|
///
|
|
/// // 에러 메시지 직접 설정 (Validation 없이)
|
|
/// sizeField.ErrorMessage = "서버 오류가 발생했습니다.";
|
|
/// sizeField.ErrorMessage = ""; // 오류 제거
|
|
/// </code>
|
|
/// <para><b>UXML에서 사용:</b></para>
|
|
/// <code>
|
|
/// <!-- 네임스페이스 선언 -->
|
|
/// <UXML xmlns:utk="UVC.UIToolkit">
|
|
/// <!-- 기본 Vector2 필드 -->
|
|
/// <utk:UTKVector2Field label="위치" />
|
|
///
|
|
/// <!-- 커스텀 라벨 -->
|
|
/// <utk:UTKVector2Field label="크기" x-label="Width" y-label="Height" />
|
|
///
|
|
/// <!-- 비활성화 -->
|
|
/// <utk:UTKVector2Field label="비활성화" is-enabled="false" />
|
|
///
|
|
/// <!-- 읽기 전용 -->
|
|
/// <utk:UTKVector2Field label="고정 크기" is-readonly="true" />
|
|
///
|
|
/// <!-- 에러 메시지 (C#에서 Validation 설정 권장) -->
|
|
/// <utk:UTKVector2Field label="크기" error-message="크기는 양수여야 합니다." />
|
|
///
|
|
/// <!-- label min-width 설정 -->
|
|
/// <utk:UTKVector2Field label="크기" label-min-width="120" />
|
|
/// </UXML>
|
|
/// </code>
|
|
/// <para><b>Label Min-Width 설정:</b></para>
|
|
/// <code>
|
|
/// // label이 있을 때 .unity-label의 min-width를 설정
|
|
/// var vec2Field = new UTKVector2Field("크기");
|
|
/// vec2Field.LabelMinWidth = 120f; // 120px
|
|
/// </code>
|
|
/// <para><b>실제 활용 예시:</b></para>
|
|
/// <code>
|
|
/// // RectTransform 크기 조절
|
|
/// var sizeField = new UTKVector2Field("UI 크기");
|
|
/// sizeField.Value = rectTransform.sizeDelta;
|
|
/// sizeField.OnValueChanged += (size) => {
|
|
/// rectTransform.sizeDelta = size;
|
|
/// };
|
|
///
|
|
/// // 스프라이트 피벗 설정
|
|
/// var pivotField = new UTKVector2Field("피벗");
|
|
/// pivotField.XLabel = "X (0~1)";
|
|
/// pivotField.YLabel = "Y (0~1)";
|
|
/// pivotField.Value = new Vector2(0.5f, 0.5f); // 중앙
|
|
/// </code>
|
|
/// </example>
|
|
[UxmlElement]
|
|
public partial class UTKVector2Field : Vector2Field, IDisposable
|
|
{
|
|
#region Constants
|
|
private const string USS_PATH = "UIToolkit/Input/UTKVector2Field";
|
|
#endregion
|
|
|
|
#region Fields
|
|
private bool _disposed;
|
|
private bool _isEnabled = true;
|
|
private bool _isReadOnly = false;
|
|
private string _xLabel = "X";
|
|
private string _yLabel = "Y";
|
|
private string _errorMessage = "";
|
|
private float _labelMinWidth = -1f;
|
|
private Func<bool>? _validation;
|
|
private Label? _errorLabel;
|
|
#endregion
|
|
|
|
#region Events
|
|
/// <summary>값 변경 이벤트</summary>
|
|
public event Action<Vector2>? OnValueChanged;
|
|
#endregion
|
|
|
|
#region Properties
|
|
/// <summary>현재 값</summary>
|
|
public Vector2 Value
|
|
{
|
|
get => value;
|
|
set => this.value = value;
|
|
}
|
|
|
|
/// <summary>활성화 상태</summary>
|
|
[UxmlAttribute("is-enabled")]
|
|
public bool IsEnabled
|
|
{
|
|
get => _isEnabled;
|
|
set
|
|
{
|
|
_isEnabled = value;
|
|
SetEnabled(value);
|
|
EnableInClassList("utk-vector2-field--disabled", !value);
|
|
}
|
|
}
|
|
|
|
/// <summary>X축 라벨</summary>
|
|
[UxmlAttribute("x-label")]
|
|
public string XLabel
|
|
{
|
|
get => _xLabel;
|
|
set
|
|
{
|
|
_xLabel = value;
|
|
UpdateAxisLabels();
|
|
}
|
|
}
|
|
|
|
/// <summary>Y축 라벨</summary>
|
|
[UxmlAttribute("y-label")]
|
|
public string YLabel
|
|
{
|
|
get => _yLabel;
|
|
set
|
|
{
|
|
_yLabel = value;
|
|
UpdateAxisLabels();
|
|
}
|
|
}
|
|
|
|
/// <summary>읽기 전용 상태</summary>
|
|
[UxmlAttribute("is-readonly")]
|
|
public bool IsReadOnly
|
|
{
|
|
get => _isReadOnly;
|
|
set
|
|
{
|
|
_isReadOnly = value;
|
|
UpdateReadOnlyState();
|
|
EnableInClassList("utk-vector2-field--readonly", value);
|
|
}
|
|
}
|
|
|
|
/// <summary>에러 메시지. 비어있지 않으면 에러 상태로 표시</summary>
|
|
[UxmlAttribute("error-message")]
|
|
public string ErrorMessage
|
|
{
|
|
get => _errorMessage;
|
|
set
|
|
{
|
|
_errorMessage = value;
|
|
var hasError = !string.IsNullOrEmpty(value);
|
|
EnableInClassList("utk-vector2-field--error", hasError);
|
|
UpdateErrorLabel(hasError ? value : null);
|
|
}
|
|
}
|
|
|
|
/// <summary>검증 함수. FocusOut 시 호출되어 false 반환 시 ErrorMessage 표시</summary>
|
|
public Func<bool>? Validation
|
|
{
|
|
get => _validation;
|
|
set => _validation = value;
|
|
}
|
|
|
|
/// <summary>label이 있을 때 .unity-label의 min-width (px). -1이면 미설정</summary>
|
|
[UxmlAttribute("label-min-width")]
|
|
public float LabelMinWidth
|
|
{
|
|
get => _labelMinWidth;
|
|
set
|
|
{
|
|
_labelMinWidth = value;
|
|
ApplyLabelMinWidth();
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region Constructor
|
|
public UTKVector2Field() : base()
|
|
{
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
|
|
var uss = Resources.Load<StyleSheet>(USS_PATH);
|
|
if (uss != null)
|
|
{
|
|
styleSheets.Add(uss);
|
|
}
|
|
|
|
SetupStyles();
|
|
SetupEvents();
|
|
SubscribeToThemeChanges();
|
|
}
|
|
|
|
public UTKVector2Field(bool isReadOnly) : this()
|
|
{
|
|
_isReadOnly = isReadOnly;
|
|
UpdateReadOnlyState();
|
|
}
|
|
|
|
public UTKVector2Field(string label, bool isReadOnly = false) : this()
|
|
{
|
|
this.label = label;
|
|
_isReadOnly = isReadOnly;
|
|
UpdateReadOnlyState();
|
|
}
|
|
#endregion
|
|
|
|
#region Setup
|
|
private void SetupStyles()
|
|
{
|
|
AddToClassList("utk-vector2-field");
|
|
|
|
// 초기 라벨 설정
|
|
schedule.Execute(() =>
|
|
{
|
|
UpdateAxisLabels();
|
|
ApplyLabelMinWidth();
|
|
});
|
|
}
|
|
|
|
private void SetupEvents()
|
|
{
|
|
RegisterCallback<ChangeEvent<Vector2>>(OnFieldValueChanged);
|
|
RegisterCallback<FocusOutEvent>(OnFocusOut);
|
|
}
|
|
|
|
private void SubscribeToThemeChanges()
|
|
{
|
|
UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged;
|
|
RegisterCallback<AttachToPanelEvent>(OnAttachToPanelForTheme);
|
|
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanelForTheme);
|
|
}
|
|
|
|
private void OnAttachToPanelForTheme(AttachToPanelEvent evt)
|
|
{
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged;
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
}
|
|
|
|
private void OnDetachFromPanelForTheme(DetachFromPanelEvent evt)
|
|
{
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
}
|
|
|
|
private void OnThemeChanged(UTKTheme theme)
|
|
{
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
}
|
|
|
|
private void UpdateAxisLabels()
|
|
{
|
|
// Vector2Field의 내부 FloatField들을 찾아서 라벨 변경
|
|
var floatFields = this.Query<FloatField>().ToList();
|
|
if (floatFields.Count >= 2)
|
|
{
|
|
floatFields[0].label = _xLabel;
|
|
floatFields[1].label = _yLabel;
|
|
}
|
|
}
|
|
|
|
private void UpdateReadOnlyState()
|
|
{
|
|
// 내부 FloatField들의 TextInput을 찾아서 읽기 전용 설정
|
|
var textInputs = this.Query<TextInputBaseField<float>>().ToList();
|
|
foreach (var textInput in textInputs)
|
|
{
|
|
textInput.isReadOnly = _isReadOnly;
|
|
}
|
|
}
|
|
|
|
private void ApplyLabelMinWidth()
|
|
{
|
|
if (string.IsNullOrEmpty(label)) return;
|
|
var labelElement = this.Q<Label>(className: "unity-label");
|
|
if (labelElement == null) return;
|
|
|
|
if (_labelMinWidth >= 0)
|
|
{
|
|
labelElement.style.minWidth = _labelMinWidth;
|
|
}
|
|
else
|
|
{
|
|
labelElement.style.minWidth = StyleKeyword.Null;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region Event Handlers
|
|
private void OnFieldValueChanged(ChangeEvent<Vector2> evt)
|
|
{
|
|
OnValueChanged?.Invoke(evt.newValue);
|
|
}
|
|
|
|
private void OnFocusOut(FocusOutEvent evt)
|
|
{
|
|
RunValidation();
|
|
}
|
|
#endregion
|
|
|
|
#region Methods
|
|
/// <summary>
|
|
/// 강제로 Validation을 실행하여 에러 상태를 업데이트합니다.
|
|
/// </summary>
|
|
/// <returns>Validation이 null이면 true, 아니면 Validation 결과</returns>
|
|
public bool Validate()
|
|
{
|
|
return RunValidation();
|
|
}
|
|
|
|
/// <summary>에러 상태를 수동으로 해제합니다.</summary>
|
|
public void ClearError()
|
|
{
|
|
ErrorMessage = "";
|
|
}
|
|
|
|
private bool RunValidation()
|
|
{
|
|
if (_validation == null) return true;
|
|
|
|
var isValid = _validation.Invoke();
|
|
if (isValid)
|
|
{
|
|
// 검증 통과 시 에러 상태 해제
|
|
EnableInClassList("utk-vector2-field--error", false);
|
|
UpdateErrorLabel(null);
|
|
}
|
|
else
|
|
{
|
|
// 검증 실패 시 에러 상태 표시
|
|
EnableInClassList("utk-vector2-field--error", true);
|
|
UpdateErrorLabel(_errorMessage);
|
|
}
|
|
return isValid;
|
|
}
|
|
|
|
private void UpdateErrorLabel(string? message)
|
|
{
|
|
if (string.IsNullOrEmpty(message))
|
|
{
|
|
// 에러 라벨 숨기기 (존재하면)
|
|
if (_errorLabel != null)
|
|
{
|
|
_errorLabel.style.display = DisplayStyle.None;
|
|
}
|
|
return;
|
|
}
|
|
|
|
// 에러 라벨 생성 (지연 생성 - 필요할 때만)
|
|
if (_errorLabel == null)
|
|
{
|
|
_errorLabel = new Label();
|
|
_errorLabel.AddToClassList("utk-vector2-field__error-message");
|
|
_errorLabel.style.display = DisplayStyle.None;
|
|
Add(_errorLabel);
|
|
}
|
|
|
|
_errorLabel.text = message;
|
|
_errorLabel.style.display = DisplayStyle.Flex;
|
|
}
|
|
#endregion
|
|
|
|
#region IDisposable
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
UnregisterCallback<AttachToPanelEvent>(OnAttachToPanelForTheme);
|
|
UnregisterCallback<DetachFromPanelEvent>(OnDetachFromPanelForTheme);
|
|
UnregisterCallback<ChangeEvent<Vector2>>(OnFieldValueChanged);
|
|
UnregisterCallback<FocusOutEvent>(OnFocusOut);
|
|
|
|
OnValueChanged = null;
|
|
_validation = null;
|
|
_errorLabel = null;
|
|
}
|
|
#endregion
|
|
}
|
|
}
|