Unity技巧:轻松实现鼠标悬停文本时的动态变色效果

文章目录


前言

在游戏或应用中,给用户的界面添加一些小的互动效果能让它们更加吸引人。比如,当策划要求你这样做的时候 ,当用户将鼠标悬停在文字上时,文字颜色改变,这样的效果会让界面看起来更有趣。本文将教你如何在Unity中实现这个效果,将写好的脚本挂载到按钮上即可。


一、Text

csharp 复制代码
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 = GetComponentInChildren<Text>();
        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

csharp 复制代码
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 = GetComponentInChildren<TMP_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的颜色格式进行配置的话,使用以下逻辑封装成适合的方法。

csharp 复制代码
Color sample;
ColorUtility.TryParseHtmlString("#3790E7", out sample);
textMeshPro.color = sample;

Text.color = ColorUtility.TryParseHtmlString("#3790E7", out var color) ? color : Color.blue;

总结

使用这些脚本,你可以轻松地在Unity中实现鼠标悬停时改变文字颜色的效果。

相关推荐
仙魁XAN2 小时前
Unity 设计模式 之 创造型模式-【工厂方法模式】【抽象工厂模式】
unity·设计模式·工厂方法模式·抽象工厂模式
我要吐泡泡了哦4 小时前
GAMES104:15 游戏引擎的玩法系统基础-学习笔记
笔记·学习·游戏引擎
躺下睡觉~12 小时前
Unity-Transform类-父子关系
java·unity·游戏引擎
躺下睡觉~12 小时前
Unity-Transform类-缩放和看向
unity·游戏引擎
君莫愁。14 小时前
【Unity】检测鼠标点击位置是否有2D对象
unity·c#·游戏引擎
咩咩觉主15 小时前
Unity实战案例全解析:PVZ 植物卡片状态分析
unity·c#·游戏引擎
蓝裕安18 小时前
伪工厂模式制造敌人
开发语言·unity·游戏引擎
谢泽浩1 天前
Unity 给模型贴上照片
unity·游戏引擎
z2014z1 天前
Unity Resource System 优化笔记
unity·游戏引擎
王维志1 天前
Unity 高亮插件HighlightPlus介绍
unity·游戏引擎