본문 바로가기
[Unity]

[Unity] 자식 오브젝트와 함께 Color Tint를 적용하는 버튼

by 김기승 2022. 12. 12.

본 글에서는 버튼의 Color Tint가 하위 오브젝트에도 적용될 수 있도록 하는 스크립트를 알아본다.

이 스크립트는 가장 아래에 배치되어 있다.

Canvas에 Button을 생성하고, Highlighted Color와 Pressed Color의 알파 값을 어느 정도 낮추어 준다.

이는 마우스 오버나 클릭이 발생했을 때 불투명도를 낮춰주기 위함이다.

이번에는 Canvas에 Button을 생성한 후, Button 컴포넌트를 MultipleColorTintButton 컴포넌트로 대체한다.

또한, Button과 동일하게 Highlighted Color와 Pressed Color의 알파 값을 어느 정도 낮추어 준다.

Hierarchy는 이러하다.


▼ 결과.gif


using UnityEngine;
using UnityEngine.UI;
using System;

public class MultipleColorTintButton : Button
{
    private Graphic[] m_graphics;
    protected Graphic[] Graphics
    {
        get
        {
            if (m_graphics == null) //캐싱이 되지 않았다면
                m_graphics = targetGraphic.transform.GetComponentsInChildren<Graphic>(); //자식 오브젝트로부터 Graphic 컴포넌트 지정
            return m_graphics;
        }
    }

    protected override void DoStateTransition(SelectionState state, bool instant)
    {
        Color color;
        switch (state)
        {
            case SelectionState.Normal:
                color = colors.normalColor;
                break;
            case SelectionState.Highlighted:
                color = colors.highlightedColor;
                break;
            case SelectionState.Pressed:
                color = colors.pressedColor;
                break;
            case SelectionState.Selected:
                color = colors.selectedColor;
                break;
            case SelectionState.Disabled:
                color = colors.disabledColor;
                break;
            default:
                color = Color.black;
                break;
        }

        if (gameObject.activeInHierarchy)
        {
            switch (transition)
            {
                case Transition.ColorTint: //Color Tint
                    ColorTween(color * colors.colorMultiplier, instant);
                    break;
                default:
                    throw new NotSupportedException();
            }
        }
    }

    private void ColorTween(Color targetColor, bool instant)
    {
        if (targetGraphic == null) return;
        for (int i = 0; i < Graphics.Length; ++i) Graphics[i].CrossFadeColor(targetColor, (!instant) ? colors.fadeDuration : 0f, true, true);
    }
}

※ 단, 자식 오브젝트는 Graphic 컴포넌트를 상속받는 컴포넌트여야 작동한다(Image, Text, TextMeshProUGUI, ...).

댓글