반응형

Content Size Fitter가 사용된 오브젝트는 설정에 따라 Rect Transform의 Width, Height 필드가 잠기고 Some values driven by ContentSizeFitter라는 메세지가 표시된다.

 

Content Size Filter

 

Rect Transform

 

그리고 이 Rect Transform의 sizeDelta(Width, Height 정보가 있는 Vector2 구조체)를 스크립트에서 확인해 보면 (0, 0)을 반환하는 경우가 발생할 수 있다. 아래 코드를 참고해서 해결하자.

 

void Start()
{   
    RectTransform[] crt = GetComponentsInChildren<RectTransform>();
    // 자식 오브젝트와 같은 컴포넌트를 가진 상태에서 GetComponentInChildren<>()을 사용해 그
    // 컴포넌트를 가져오면 항상 자신의 컴포넌트가 리턴된다. 또, GetComponenetsInChildren<>()
    // 사용시 0번 인덱스도 자신이 된다.

    LayoutRebuilder.ForceRebuildLayoutImmediate(crt[1]);
    //Canvas.ForceUpdateCanvases();
    // LayoutRebuilder.ForceRebuildLayoutImmediate()대신 위 함수를 사용해도 된다.
    // 하지만 비효율적.

    Vector2 size = crt[1].sizeDelta;
    //Vector2 size = new Vector2(crt[1].rect.width, crt[1].rect.height);
    
    Debug.Log(crt[1]);
    Debug.Log(size);

    SpriteRenderer sr = GetComponent<SpriteRenderer>();
    sr.size = size;
    // Sprite Renderer 사이즈를 자식 오브젝트 Rect Transform 사이즈로 설정한다.
}

 

부모 오브젝트에 Rect Transform, Sprite Renderer 가 있는 상태에서 위 코드가 포함된 스크립트를 추가했다. 자식 오브젝트에도 Rect Transform이 있고 Content Size Fitter가 추가되어 있다.

sizeDelta 정보에 접근하기 전, ForceRebuildLayoutImmediate()(또는 ForceUpdateCanvases()) 를 먼저 실행하지 않으면 Rect Transform에 필요한 계산이 끝나지 않아 부정확한 정보가 넘어올 수 있다.

 

Rect Transform Details

Note that some RectTransform calculations are performed at the end of a frame, just before calculating UI vertices, in order to ensure that they are up to date with all the latest changes performed throughout the frame. This means that they haven't yet been calculated for the first time in the Start callback and first Update callback.
You can work around this by creating a Start() callback and adding Canvas.ForceUpdateCanvases() method to it. This will force Canvas to be updated not at the end of the frame, but when that method is called.

 

반응형
Posted by J-sean
: