Shegotwet/Assets/Scripts/Util/MatchRectToCollider.cs

29 lines
695 B
C#

using UnityEngine;
[RequireComponent(typeof(RectTransform))]
[RequireComponent(typeof(BoxCollider2D))]
public class MatchRectToCollider : MonoBehaviour
{
void UpdateCollider()
{
RectTransform rt = GetComponent<RectTransform>();
BoxCollider2D col = GetComponent<BoxCollider2D>();
// RectTransform의 크기를 collider size로 적용
col.size = rt.rect.size;
// pivot 때문에 위치가 달라질 수 있으므로 offset 조정
col.offset = rt.rect.center;
}
void Start()
{
UpdateCollider();
}
// 에디터에서 값 바뀔 때도 자동 반영
void OnValidate()
{
UpdateCollider();
}
}