UnityUI mouse hover, image zoom effect
Method 1: Create a transparent image mask, and the code controls image scaling
- Create a sub-image selected under pic2, and unify the parameter values of the Rect Transform component of image and selected
create subimage
Unify the Rect Transform parameter value by copying and pasting
Note: Scale is preferably 1:1:1
- Create a ModeHighLighting script, hang it on pic2, and assign the image selected to the script variable
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) //禁用遮罩
}
}
- Adjust the transparency of the image selected, set to inactive
Adjust image transparency
set to inactive
Method 2: Use the button component to make a mask effect, and the code controls the image zoom
- Add button component on pic2, set Highlighted Color
- Create ModeHighLighting script, also hang on 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)
}
}