Unity 實現(xiàn)鼠標滑過UI時觸發(fā)動畫的操作
在有些需求中會遇到,當(dāng)鼠標滑過某個UI物體上方時,為了提醒用戶該物體是可以交互時,我們需要添加一個動效和提示音。這樣可以提高產(chǎn)品的體驗感。
解決方案
1、給需要有動畫的物體制作相應(yīng)的Animation動畫。(相同動效可以使用同一動畫復(fù)用)
2、給需要有動畫的物體添加腳本。腳本如下:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class OnBtnEnter : MonoBehaviour, IPointerEnterHandler,IPointerExitHandler
{
//鼠標進入按鈕觸發(fā)音效和動畫
public void OnPointerEnter(PointerEventData eventData)
{
// AudioManager.audioManager.PlayEnterAudio();//這里可以將播放觸發(fā)提示音放在這里,沒有可以提示音可以將該行注釋掉
if (gameObject.GetComponent<Animation>()!=null) {
if ( gameObject.GetComponent<Animation>() .isPlaying) {
return;
}
gameObject.GetComponent<Animation>().wrapMode = WrapMode.Loop;
gameObject.GetComponent<Animation>().Play();
}
}
//鼠標離開時關(guān)閉動畫
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()實現(xiàn)鼠標懸停時各種效果(UI+3D物體)
OnMouseEnter() 鼠標進入
OnMouseExit() 鼠標離開
一、3D物體

OnMouseEnter(),OnMouseExit()都是通過collider觸發(fā)的,且碰撞器不能是trigger,鼠標進入,或離開collider時,自動調(diào)用這兩個函數(shù)。
另外,OnMouseOver()類似,與OnMouseEnter()區(qū)別是,OnMouseOver()會當(dāng)鼠標在該物體上collider內(nèi)時,每幀調(diào)用1次,OnMouseEnter()僅在鼠標進入時調(diào)用1次。
二、UI
UI部分通過eventTrigger組件實現(xiàn)類似功能
using 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(),所以想實現(xiàn)漸變效果,可通過添加一個bool flag判斷,在update()方法中實現(xiàn)逐幀漸變效果。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
C#生成設(shè)置范圍內(nèi)的Double類型隨機數(shù)的方法
這篇文章主要介紹了C#生成設(shè)置范圍內(nèi)的Double類型隨機數(shù)的方法,對于C#的初學(xué)者有很好的借鑒價值,需要的朋友可以參考下2014-08-08
C#如何將DataTable導(dǎo)出到Excel解決方案
由于公司項目中需要將系統(tǒng)內(nèi)用戶操作的所有日志進行轉(zhuǎn)存?zhèn)浞?,考慮到以后可能還需要還原,所以最后決定將日志數(shù)據(jù)備份到Excel中2012-11-11
解決unity rotate旋轉(zhuǎn)物體 限制物體旋轉(zhuǎn)角度的大坑
這篇文章主要介紹了解決unity rotate旋轉(zhuǎn)物體 限制物體旋轉(zhuǎn)角度的大坑,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04
在C#中調(diào)用Python代碼的兩種實現(xiàn)方式
這篇文章主要介紹了在C#中調(diào)用Python代碼的兩種實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03

