圖片按鈕的兩態變化鼠標左鍵按下down和彈起up所觸發的事件
編寫兩個腳本文件
一個是點擊按鈕的圖片變化(UI代碼)
1 using UnityEngine; 2 using System.Collections; 3 4 public class MyUIButton : MonoBehaviour 5 { 6 public Texture2D[] btn; 7 public string doUpMethodName; 8 public string doDownMethodName; 9 Rect rc; 10 int index = 0; 11 12 void Update() 13 { 14 if(Input.GetMouseButtonUp(0)) 15 { 16 rc = guiTexture.pixelInset; 17 rc.x += transform.position.x * Screen.width; 18 rc.y += transform.position.y * Screen.height; 19 if(rc.Contains(Input.mousePosition)) 20 { 21 index = 1; 22 SendMessage(doUpMethodName,index);//按鈕彈起時的事件觸發 23 } 24 } 25 26 if(Input.GetMouseButtonDown(0)) 27 { 28 rc = guiTexture.pixelInset; 29 rc.x += transform.position.x * Screen.width; 30 rc.y += transform.position.y * Screen.height; 31 if(rc.Contains(Input.mousePosition)) 32 { 33 index = 0; 34 SendMessage(doDownMethodName);//按鈕按下時的事件觸發 35 } 36 } 37 guiTexture.texture = btn[index]; 38 } 39 }
一個是點擊按鈕觸發的事件(邏輯代碼)
1 using UnityEngine; 2 using System.Collections; 3 4 public class DoAction : MonoBehaviour 5 { 6 void DoDownMethodName() 7 { 8 Debug.Log("down.down"); 9 } 10 11 void DoUpMethodName() 12 { 13 Debug.Log("up.up"); 14 } 15 16 }
將這兩個腳本都綁定到一個GameObject上,並附加相應的變量屬性值,如圖
PS:1. DoAction這個接收Message的腳本類,必須繼承MonoBehaviour,否則會報出沒有邏輯處理的那個方法名
2. 圖片不能用Transform.Scale縮放,要縮放的話就直接更改圖片的width和height
3. 腳本中不能出現中文注釋,會出現腳本的解析錯誤,終端報出"CS8025 Parsing error",為了解決這個error,查遍Unity3d的官方論壇后仍沒有結果(國內的基本沒有關於Unity3d的好論壇,你懂的),思來想去這個問題不應該不會在論壇沒有啊,於是乎開始了第N次的查看所寫的代碼確定無誤后,不知怎么地想到了本地化問題,抱着試試看的心理把中文注釋刪掉,結果error沒有了。為這個所謂的操蛋的error花費了近1個小時的時間!(我用的是Unity3.4,其他版本未知)