UnityUI 鼠标悬停,图像放大效果

方法一:创建透明图像遮罩,代码控制图像缩放

  1. 在pic2下创建子图像selected,统一image和selected的Rect Transform组件参数值

创建子图像
创建子图像

统一Rect Transfor参数值
通过复制粘贴,统一Rect Transfor参数值

注意点
注意:Scale最好是1:1:1

  1. 创建ModeHighLighting脚本,挂在pic2上,并将图像selected赋值给脚本变量
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class ModeHighLighting : MonoBehaviour,IPointerEnterHandler,IPointerExitHandler //IPointerEnterHandler用于检测鼠标何时开始悬停在某个游戏对象上;IPointerExitHandler用于检测鼠标何时停止悬停在游戏对象上
{
    
    
    public GameObject beSelected; //遮罩
    public float size=1.2f; //放大倍数
    public float normalSize = 1f; //原缩放值scale(1,1,1)
   
    public void OnPointerEnter(PointerEventData eventData) //检测鼠标悬停在物体上时运行
    {
    
    
        beSelected.SetActive(true); //激活遮罩
        transform.localScale = new Vector3(size, size, size); //放大图像
        //transform.localScale += Vector3.one * size; //Vector3.one是Vector3(1, 1, 1)的简写
    }

    public void OnPointerExit(PointerEventData eventData) //检测鼠标离开物体时运行
    {
    
    
        transform.localScale = new Vector3(normalSize,normalSize,normalSize); //还原图像大小
        //transform.localScale = Vector3.one;
        beSelected.SetActive(false) //禁用遮罩
    }

    void OnEnable() //只在程序启动时执行一次
    {
    
    
        transform.localScale = new Vector3(normalSize, normalSize, normalSize); //初始化图像大小
        //transform.localScale = Vector3.one;
        beSelected.SetActive(false) //禁用遮罩
    }
}

将图像selected赋值给脚本变量

  1. 调整图像selected的透明度,设置为未激活状态

调整图像透明度
调整图像透明度

设置为未激活状态
设置为未激活状态

方法二:使用button组件做遮罩效果,代码控制图像缩放

  1. 在pic2上添加button组件,设置Highlighted Color
    设置Highlighted Color
  2. 创建ModeHighLighting脚本,也挂在pic2上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class ModeHighLighting : MonoBehaviour,IPointerEnterHandler,IPointerExitHandler
{
    
    
    //public GameObject beSelected;
    public float size=1.2f;
    public float normalSize = 1f;
   
    public void OnPointerEnter(PointerEventData eventData)
    {
    
    
        //beSelected.SetActive(true);
        transform.localScale = new Vector3(size, size, size);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
    
    
        transform.localScale = new Vector3(normalSize,normalSize,normalSize);
        //beSelected.SetActive(false)
    }

    void OnEnable()
    {
    
    
        transform.localScale = new Vector3(normalSize, normalSize, normalSize);
        //beSelected.SetActive(false)
    }
}

猜你喜欢

转载自blog.csdn.net/yxy171229/article/details/128294066