由於NGUI的onPress只有在物件被點擊和放開時才會被處發...
所以若希望按下按鍵時,就一直處發;放開按鍵時,就立刻停止的話,必須搭配Update()來處理這事件
一樣先引入NGUI,然後放置如下
點選Image Button,然後按下 Add Component 新增Event Listener
再來新增一個C# script 且命名為move
接著開始撰寫程式碼
using UnityEngine;
public class move : MonoBehaviour
{
private GameObject target;//被按下的物件
private GameObject cube;//要轉動的物件
private bool isPress = false;//確認是否已被按下,預設為沒有被按下
private void Start()
{
cube = GameObject.Find("UI Root/Cube");//取得要轉動的物件
target = GameObject.Find("UI Root/Image Button");//取得被按下的物件
UIEventListener.Get(target).onPress = cubeEvent;//註冊事件
}
private void cubeEvent(GameObject go, bool state)
{
if (state == true)//若被按下
{
isPress = true;
}
else//若放開
{
isPress = false;
}
}
private void Update ()
{
if (isPress == true)//若是被按下了,則旋轉Cube
{
cube.transform.Rotate(new Vector3(5, 0, 0));
}
}
}
然後將此程式碼拖曳到任何元件上(在此我拖曳到UI Root上)
開始執行!
當壓下Image Button時,Cube將會轉動;而放開Image Button時,Cube立即停止轉動
留言列表