街区网站建设的意义,宁波建设工程学校,襄阳网站seo,洛阳做网站排名文章目录 前言一、Text二、TMP_Text二、颜色转换总结 前言
在游戏或应用中#xff0c;给用户的界面添加一些小的互动效果能让它们更加吸引人。比如#xff0c;当策划要求你这样做的时候 #xff0c;当用户将鼠标悬停在文字上时#xff0c;文字颜色改变#xff0c;这样的效… 文章目录 前言一、Text二、TMP_Text二、颜色转换总结 前言
在游戏或应用中给用户的界面添加一些小的互动效果能让它们更加吸引人。比如当策划要求你这样做的时候 当用户将鼠标悬停在文字上时文字颜色改变这样的效果会让界面看起来更有趣。本文将教你如何在Unity中实现这个效果将写好的脚本挂载到按钮上即可。 一、Text
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;public class TextColorChange : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{public Color normalColor Color.blue; // 默认颜色public Color hoverColor Color.white; // 悬停时颜色private Text textComponent;private void Start(){textComponent GetComponentInChildrenText();if (textComponent null){Debug.LogError(没有找到Text组件请确保文本对象是Button的子对象并且拥有Text组件。);}else{textComponent.color normalColor;}}public void OnPointerEnter(PointerEventData eventData){if (textComponent ! null){textComponent.color hoverColor; // 悬浮时将字体颜色改为悬停颜色}}public void OnPointerExit(PointerEventData eventData){if (textComponent ! null){textComponent.color normalColor; // 离开时将字体颜色还原为默认颜色}}
}
二、TMP_Text
using UnityEngine;
using TMPro;
using UnityEngine.EventSystems;public class TMPTextColorChange : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{public Color normalColor Color.blue; // 默认颜色public Color hoverColor Color.white; // 悬停时颜色private TMP_Text textMeshPro;private void Start(){textMeshPro GetComponentInChildrenTMP_Text();if (textMeshPro null){Debug.LogError(没有找到TMP_Text组件请确保文本对象是Button的子对象并且拥有TMP_Text组件。);}else{textMeshPro.color normalColor;}}public void OnPointerEnter(PointerEventData eventData){if (textMeshPro ! null){textMeshPro.color hoverColor; // 悬浮时将字体颜色改为悬停颜色}}public void OnPointerExit(PointerEventData eventData){if (textMeshPro ! null){textMeshPro.color normalColor; // 离开时将字体颜色还原为默认颜色}}
}
二、颜色转换
如果要使用配置加载或者用类似#xxxxx的颜色格式进行配置的话使用以下逻辑封装成适合的方法。
Color sample;
ColorUtility.TryParseHtmlString(#3790E7, out sample);
textMeshPro.color sample;Text.color ColorUtility.TryParseHtmlString(#3790E7, out var color) ? color : Color.blue;总结
使用这些脚本你可以轻松地在Unity中实现鼠标悬停时改变文字颜色的效果。