Unity/기능구현

[Unity] Debug Log 출력문에 색상 변경하기

민트초밥 2022. 4. 19. 15:00

목표 : 유니티에서 Log를 출력에 출력되는 문장의 색을 변경해보자.

 

 

가장 간단한 방법으로는 마크업 태그인 <color> 태그를 이용해서 텍스트의 색을 변경할 수 있다.

void Start()
{
    Debug.Log("<color=#FF0000>빨간색</color>");
    Debug.Log("<color=#00FF00>초록색</color>");
    Debug.Log("<color=#0000FF>파란색</color>");
}

 

 

 

 

하지만 매번 이렇게 색을 변경하는 건 번거롭기 때문에 함수로 만들어보자.

Unity 메뉴얼에 들어가면 Debug.Logformat이라는 함수가 있는데 이 함수를 이용해보도록 하자.

 

 

Unity - Scripting API: Debug.LogFormat

For formatting details, see the MSDN documentation on Composite Formatting. Rich text markup can be used to add emphasis. See the manual page about rich text for details of the different markup tags available. See Also: Debug.unityLogger, ILogger.

docs.unity3d.com

 

 

 

string.format 함수와 같은 형태로 Debug.LogFormat 함수를 사용해서 문자열과 해당 문자열에 대입할 값들을 순서대로 써주면 함수를 사용할 수 있다.

void Start()
{
    CustomDebug();
}

private void CustomDebug()
{
    Debug.LogFormat("<color={0}>{1}</color>", "#FFFF00", "안녕하세요!!!");
}

 

 

 

하지만 아직도 색상을 변경해주는 부분을 자유롭게 변경할 수 없기 때문에 조금 더 수정해보자.

이번에는 매개변수 값으로 색상값과 출력문을 받아온다.

void Start()
{
    CustomDebug("#FFFF00", "안녕하세요!!!");
}

private void CustomDebug(string color, string text)
{
    Debug.LogFormat("<color={0}>{1}</color>", color, text);
}

 

 

 

마지막으로 유니티에 미리 정의된 색상들도 사용할 수 있도록 변경한다.

예를들어 Color.red, Color.blue 이런것들...

void Start()
{
    CustomDebug("#FFFF00", "안녕하세요!!!");
    CustomDebug(Color.red, "안녕하세요!!!");
}

private void CustomDebug(string color, string text)
{
    Debug.LogFormat("<color={0}>{1}</color>", color, text);
}

private void CustomDebug(Color color, string text)
{
    string colorStr = "#" + ColorUtility.ToHtmlStringRGB(color);
    Debug.LogFormat("<color={0}>{1}</color>", colorStr, text);
}

 

오버로딩을 사용해서 매개변수만 다르게 써서 사용할 수 있도록 만들었다.

Color값을 string의 형태로 바꿔야 했기 때문에 ColorUtility.ToHtmlStringRGB() 함수를 사용했고, 이 값은 "FF0000"의 형태로 나오기 때문에 앞에 "#"을 추가해서 LogFormat에서 사용할 수 있는 형태로 바꿨다.

 

 

최종 결과 로그화면

 

반응형