Unity问答——NGUI怎么使用按键模拟鼠标点击?

     这篇博客源自我在泰课在线的回答。链接:http://www.taikr.com/group/1/thread/248

     问:NGUI怎么模拟用代码模拟控制点击

     答:   

      1. 这个问题问得好。因为在使用按键或摇杆控制时,会遇到这个问题。

  2. 先上代码:

  

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class KeyBoardControl : MonoBehaviour
 5 {
 6     private UIButton uiButton;
 7     void Start()
 8     {
 9         uiButton = GetComponent<UIButton>();
10     }
11 
12     void Update()
13     {
14         if (Input.GetKey(KeyCode.T))
15         {
16             uiButton.SetState(UIButtonColor.State.Pressed, false);
17         }
18         else
19         {
20             uiButton.SetState(UIButtonColor.State.Normal, false);
21         }
22     }
23 }

 

   3. 操作:

         将代码挂载到物体上,确保物体上有UIButton和碰撞器组件。

  4. 讲解:

         4.1 最重要的是UIButton的这个方法 public override void SetState (State state, bool immediate)。第一个参数state是要设置的状态,第二个参数immediate指是否立即转变状态。设为false的话,会有渐变的效果。

         4.2 在使用鼠标控制的时候,按下鼠标左键不放,状态切换为UIButtonColor.State.Pressed,松开鼠标左键,状态切换为UIButtonColor.State.Normal。

         4.3 为了模拟鼠标左键的按下与松开,可以再某一个键按下不放时将状态设置为UIButtonColor.State.Pressed,按键松开时将状态设置为UIButtonColor.State.Normal。

posted @ 2014-10-01 00:26  xiaohu2009  阅读(2199)  评论(0编辑  收藏  举报