41 lines
1.0 KiB
C#
41 lines
1.0 KiB
C#
|
|
using UnityEngine;
|
||
|
|
|
||
|
|
[RequireComponent(typeof(SpriteRenderer))]
|
||
|
|
[ExecuteInEditMode]
|
||
|
|
public class BackgroundFitter : MonoBehaviour
|
||
|
|
{
|
||
|
|
#if UNITY_EDITOR
|
||
|
|
public bool SetFit = false;
|
||
|
|
|
||
|
|
private void Update()
|
||
|
|
{
|
||
|
|
if (SetFit)
|
||
|
|
{
|
||
|
|
SetFit = false;
|
||
|
|
Awake();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
#endif
|
||
|
|
|
||
|
|
void Awake()
|
||
|
|
{
|
||
|
|
SpriteRenderer sr = GetComponent<SpriteRenderer>();
|
||
|
|
if (sr.sprite == null) return;
|
||
|
|
|
||
|
|
// 스프라이트의 원래 크기(픽셀 단위)
|
||
|
|
float spriteWidth = sr.sprite.bounds.size.x;
|
||
|
|
float spriteHeight = sr.sprite.bounds.size.y;
|
||
|
|
|
||
|
|
// 카메라
|
||
|
|
Camera cam = Camera.main;
|
||
|
|
float worldScreenHeight = cam.orthographicSize * 2f; // 세로 크기(월드 단위)
|
||
|
|
float worldScreenWidth = worldScreenHeight * cam.aspect; // 가로 크기(월드 단위)
|
||
|
|
|
||
|
|
// 배경 스케일 계산
|
||
|
|
transform.localScale = new Vector3(
|
||
|
|
worldScreenWidth / spriteWidth,
|
||
|
|
worldScreenHeight / spriteHeight,
|
||
|
|
1f
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|