Unity 實(shí)現(xiàn)鼠標(biāo)滑過UI時觸發(fā)動畫的操作
在有些需求中會遇到,當(dāng)鼠標(biāo)滑過某個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
{
//鼠標(biāo)進(jìn)入按鈕觸發(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();
}
}
//鼠標(biāo)離開時關(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();
}
}
}
補(bǔ)充:unity 通過OnMouseEnter(),OnMouseExit()實(shí)現(xiàn)鼠標(biāo)懸停時各種效果(UI+3D物體)
OnMouseEnter() 鼠標(biāo)進(jìn)入
OnMouseExit() 鼠標(biāo)離開
一、3D物體

OnMouseEnter(),OnMouseExit()都是通過collider觸發(fā)的,且碰撞器不能是trigger,鼠標(biāo)進(jìn)入,或離開collider時,自動調(diào)用這兩個函數(shù)。
另外,OnMouseOver()類似,與OnMouseEnter()區(qū)別是,OnMouseOver()會當(dāng)鼠標(biāo)在該物體上collider內(nèi)時,每幀調(diào)用1次,OnMouseEnter()僅在鼠標(biāo)進(jìn)入時調(diào)用1次。
二、UI
UI部分通過eventTrigger組件實(shí)現(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(),所以想實(shí)現(xiàn)漸變效果,可通過添加一個bool flag判斷,在update()方法中實(shí)現(xiàn)逐幀漸變效果。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
C#與C++?dll之間傳遞字符串string?wchar_t*?char*?IntPtr問題
C#與C++?dll之間傳遞字符串string?wchar_t*?char*?IntPtr問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
WPF拖動DataGrid滾動條時內(nèi)容混亂的解決方法
這篇文章主要介紹了WPF拖動DataGrid滾動條時內(nèi)容混亂的解決方法2016-10-10
C#的Socket實(shí)現(xiàn)UDP協(xié)議通信示例代碼
本篇文章主要介紹了C#的Socket實(shí)現(xiàn)UDP協(xié)議通信示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01

