在有些需求中会遇到,当鼠标滑过某个UI物体上方时,为了提醒用户该物体是可以交互时,我们需要添加一个动效和提示音。这样可以提高产品的体验感。
6 J3 ~! A$ @: G- y; @# W6 e一、解决方案9 R- k# l1 E* |& a3 q0 V
1、给需要有动画的物体制作相应的Animation动画。(相同动效可以使用同一动画复用)
" \0 t" F/ \( D2、给需要有动画的物体添加脚本。脚本如下:
% K2 N" Z/ y3 W( ^1 ~! P+ W( n& uusing System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class OnBtnEnter : MonoBehaviour, IPointerEnterHandler,IPointerExitHandler
{
//鼠标进入按钮触发音效和动画
public void OnPointerEnter(PointerEventData eventData)
{
// AudioManager.audioManager.PlayEnterAudio();//这里可以将播放触发提示音放在这里,没有可以提示音可以将该行注释掉
if (gameObject.GetComponent<Animation>()!=null) {
if ( gameObject.GetComponent<Animation>() .isPlaying) {
return;
}
gameObject.GetComponent<Animation>().wrapMode = WrapMode.Loop;
gameObject.GetComponent<Animation>().Play();
}
}
//鼠标离开时关闭动画
public void OnPointerExit(PointerEventData eventData)
{
if ( gameObject.GetComponent<Animation>() != null )
{
if ( gameObject.GetComponent<Animation>().isPlaying )
{
gameObject.GetComponent<Animation>().wrapMode = WrapMode.Once;
return;
}
gameObject.GetComponent<Animation>().Stop();
}
}
} 补充:unity 通过OnMouseEnter(),OnMouseExit()实现鼠标悬停时各种效果(UI+3D物体)& o; e3 Y6 y3 a
- OnMouseEnter() 鼠标进入
- OnMouseExit() 鼠标离开
# L6 }; U0 Y0 G* ?* B- n; v, \7 @ ; |" W8 r, j: _! e$ @: l" c/ T
二、3D物体
$ U. _. P5 O6 i; P; _: _5 j
, _9 B( z( Y2 u z+ m7 N E OnMouseEnter(),OnMouseExit()都是通过collider触发的,且碰撞器不能是trigger,鼠标进入,或离开collider时,自动调用这两个函数。$ q" J7 B% E7 M/ ]9 s( T/ u
另外,OnMouseOver()类似,与OnMouseEnter()区别是,OnMouseOver()会当鼠标在该物体上collider内时,每帧调用1次,OnMouseEnter()仅在鼠标进入时调用1次。
6 c% L2 k) m5 G. R* P二、UI
$ N) |0 o% z5 r8 M( |5 u UI部分通过eventTrigger组件实现类似功能
4 e2 G! ~7 ] o X" G, Uusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;//使用text,image组件
public class eventTriggrtTest : MonoBehaviour {
public Image image;
float ColorAlpha = 0f;//图片透明程度
public float speed = 0.75f;
bool flag = false;
private void Start()
{
image.GetComponent<Image>().color = new Color(255, 255, 255, ColorAlpha);
}
void Update()
{
// Debug.Log("OnMouseEnter");
if(flag == true)
{
if (ColorAlpha <= 0.75)
{
ColorAlpha += Time.deltaTime * speed;
image.GetComponent<Image>().color = new Color(255, 255, 255, ColorAlpha);
}
}
Debug.Log(ColorAlpha);
}
public void OnMouseEnter()
{
flag = true;
}
public void OnMouseExit()
{
// Debug.Log("OnMouseExit");
flag = false;
ColorAlpha = 0;
image.GetComponent<Image>().color = new Color(255, 255, 255, ColorAlpha);
}
} 因UI无法使用OnMouseOver(),所以想实现渐变效果,可通过添加一个bool flag判断,在update()方法中实现逐帧渐变效果。& d% q2 `- U* Q+ ]" T5 d+ {" p& C) v
7 H0 s+ u8 a) D. P# z. n: Q+ ` x
|