[Unity] TextMeshPro 색 변경하기

https://forum.unity.com/threads/accessing-the-text-and-color-of-a-textmeshpro-object.703013/

 

Accessing the text and color of a textmeshpro object

Hello everyone, I am currently trying to change the text and the color of a texmeshpro object. But for some reason I cannot acces it because some...

forum.unity.com

이 글을 참고함


TextMeshPro를 사용했을 때 텍스트의 색을 바꾸고 싶으면

transform.GetComponent<TextMeshProUGUI>().color를 이용해서 바꿀 수 있다.

그리고 스크립트에서 TextMeshPro를 쓸 때는 using TMPro를 써주어야 한다.

 

예시는 텍스트와 플레이어가 충돌하면 색이 바뀌는 코드이다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class BarText : MonoBehaviour
{
    Color textColor;

    // Start is called before the first frame update
    void Start()
    {
        textColor = transform.GetComponent<TextMeshProUGUI>().color;
    }

    // Update is called once per frame
    void Update()
    {
        
    }

	private void OnTriggerEnter(Collider other)
	{
		if (other.gameObject.CompareTag("Player"))
		{
            textColor = new Color(95 / 255f, 194 / 255f, 255 / 255f);
            transform.GetComponent<TextMeshProUGUI>().color = textColor;
		}
	}

	private void OnTriggerExit(Collider other)
	{
		if (other.gameObject.CompareTag("Player"))
		{
            textColor = new Color(1, 1, 1);
            transform.GetComponent<TextMeshProUGUI>().color = textColor;
		}
	}
}