unity實現鼠標經過時ui及物體的變色操作
1、實現UI的變色
設置Highlighted Color為鼠標經過時變的顏色(Normal為常態(tài),Pressed為按下時的顏色,Disabled為禁止的顏色)

2、通過代碼實現物體的顏色改變
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cube_change : MonoBehaviour
{ private Color CubeColor;
private Texture CubeTexture;
public GameObject objCube;
// Use this for initialization
void Start ()
{ objCube = GameObject.Find("Cube");
objCube.GetComponent<Renderer>().material.color = Color.blue;
}
public void OnMouseEnter()
{
objCube.GetComponent<Renderer>().material.color = Color.red;
}
public void OnMouseExit()
{
objCube.GetComponent<Renderer>().material.color = Color.blue;
}
// Update is called once per frame
void Update ()
{
}
//+++++++++++++++++++++++++++
unity5.0之后renderer就不能使用material,需要使用GetComponent來獲取
GameObject objcub = GameObject.CreatePrimitive(PrimitiveType.Cube); objcub.AddComponent<Rigidbody>(); objcub.name = "Cube"; //設置color 使用這個來獲取material objcub.GetComponent<Renderer>().material.color = Color.blue;
補充:Unity 實現鼠標滑過UI時觸發(fā)動畫
在有些需求中會遇到,當鼠標滑過某個UI物體上方時,為了提醒用戶該物體是可以交互時,我們需要添加一個動效和提示音。這樣可以提高產品的體驗感。
解決方案
1、給需要有動畫的物體制作相應的Animation動畫。(相同動效可以使用同一動畫復用)
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();
}
}
//鼠標離開時關閉動畫
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人物接近時觸發(fā)事件或動畫demo
定義物體GameObject o;
效果:當人物接近物體時,物體觸發(fā)動畫,比如位移
1.創(chuàng)建o的動畫km和gm
2.創(chuàng)建空物體 Empty,大小稍微比o大一點,拖入o,用來接受觸發(fā)判定,防止物體移動過后觸發(fā)器跟著移動,勾選 is trigger
2.人物控制器
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorController : MonoBehaviour
{
private Animation ani;
void Start() {
//獲取子組件下的第一個組件,再獲取子組件animation,
//如果是獲取自身組件,直接GetComponent<XXX>()
ani = transform.GetChild(0).GetComponent<Animation>();
}
private void OnTriggerEnter(Collider other){
//當物體接觸到時則播放animation中的km動畫
ani.Play("km");
}
private void OnTriggerExit(Collider other){
//當物體接觸到時則播放animation中的gm動畫
ani.Play("gm");
}
void Update()
{
}
}
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章
C#四舍五入MidpointRounding.AwayFromZero解析
這篇文章主要介紹了C#四舍五入MidpointRounding.AwayFromZero,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05

