본문 바로가기

Unity3D/C#

유니티 랜덤 색상 추출, RGBA color to hex code

반응형

Random Color

 

 

 일반적인 UI를 가지고 있는 프로그래밍할 수 있는 엔진에는 다양한 요소들이 있지만 그중 빠질 수 없는 요소는 색상입니다. 그림판, 포토샵, 심지어는 워드나 파워포인트에서도 색상이라는 요소는 반드시 존재합니다. 색상은 크게 2가지로 존재한다고 볼 수 있습니다. 바로 색상과 그 색상을 나타내는 고유의 색상 코드입니다. 색상 코드는 보통 0~F까지의 헥사코드로 RGB는 6자리, 알파를 포함한 RGBA는 8자리의 코드를 가지고 있습니다. 예를 들어 RGB는 FFFFFF은 흰색이고 RGBA는 알파가 추가된 것으로 FFFFFFFF을 해야 투명하지 않은 흰색이 나옵니다. 유니티에도 마찬가지로 색상이라는 개념이 있습니다. 색상 코드로 색상을 변경할 수도 있고 반대로 색상으로 색상 코드를 출력할 수도 있습니다. 또 유니티에는 랜덤으로 임의의 값을 출력하는 함수들이 있는데 랜덤 함수 중에는 색상을 랜덤하게 뽑을 수 있는 기능이 있습니다. 바로 Random.ColorHSV 함수인데 범위를 지정할 수 있습니다. 기본은 전체 범위이지만 hue에 대한 범위나 saturation에 대한 범위, value에 대한 범위를 float 값으로 0~1 사이의 값으로 범위를 지정할 수 있습니다. 또한 ColorUtility라는 컬러 관련 기능을 모아놓은 Class가 있는데 ToHtmlStringRGBA을 사용하면 색상을 색상 코드로 반환받을 수 있습니다.

 

 

C# (UNITY 3D)

 

 

랜덤 색상 예시

 

랜덤 버튼을 눌러서 배경 이미지와 텍스트의 색상을 바꾸고 그 색상의 hex code를 가져오는 예시입니다.

 

 

 

using UnityEngine.UI;

 

이미지와 텍스트, 버튼을 사용하기 위해 UnityEngine.UI를 사용합니다.

 

 

할당

각 컴포넌트에 맞는 게임 오브젝트를 스크립트에 할당합니다.

 

 

 

    public Image image_color;
    public Text text_color; 
    public Text text_Title;
    public Text text_color_title; 
    public Button button_randomcolor; 

    void Start()
    {
        Init_UI();
    }
   
    private void Init_UI()
    {
        button_randomcolor.onClick.RemoveAllListeners();
        button_randomcolor.onClick.AddListener(Funciton_RandomColor);
    }

    //CodeFinder 코드파인더
    //From https://codefinder.janndk.com/ 
    private void Funciton_RandomColor()
    {
        Color color = Random.ColorHSV();
        string color_code = ColorUtility.ToHtmlStringRGBA(color);
        image_color.color = color;
        text_color.text = color_code;

        Color color_title = Random.ColorHSV();
        string color_title_code = ColorUtility.ToHtmlStringRGBA(color_title);
        text_Title.color = color_title;
        text_color_title.text = color_title_code;

        Debug.LogFormat("background color code: {0}\ntitle color code: {1}", color_code, color_title_code); 
    }  

 

변수(variable)

image_color(Image) : 색상을 바꿀 배경 이미지
text_color(Text) : 배경 이미지의 색상 코드 표시
text_Title(Text) :  색상을 바꿀 타이틀 텍스트
text_color_title(Text) : 타이틀 텍스트의 색상 코드
button_randomcolor(Button) : Funciton_RandomColor 함수의 기능을 수행할 버튼

 

함수(function)

Init_UI : 버튼에 Funciton_RandomColor 함수 기능 할당
Funciton_RandomColor : 랜덤으로 두 가지 색상을 추출해서 배경 이미지와 타이틀 텍스트에 적용하고 두 가지 색상의 색상 코드 출력

 

 

 

Color to hexcode / convert to a html color string / hexadecimal / color format / convert to hex code / 색상 변환

 

 

 

반응형