如何检测 Unity 游戏是否正在(网络键盘)或(移动触摸)上运行

Pab*_*rde 1 mobile unity-game-engine unity3d-2dtools

基本上,我有一个由移动设备中的物理键盘和触摸屏支持的统一游戏。我已经完成了物理键盘的移动脚本,现在我正在为触摸屏编写代码。

我怎样才能实现该检测功能?

我在想类似的事情......

private void HandleInput()
{
   if (detect if physical keyboard here...)
   {

        if  (Input.GetKey(KeyCode.RightArrow))
        {
            _normalizedHorizontalSpeed = 1;
        } 
        else if (Input.GetKey(KeyCode.LeftArrow))
        {
            _normalizedHorizontalSpeed = -1;
        }
   } else if (detect touch screen here...)
   {
       for (int i = 0; i < Input.touchCount; ++i)
       {
          if (Input.GetTouch(i).phase == TouchPhase.Began)
          {
             some code here...
          }
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

欣赏

Hel*_*ium 5

@ryemoss 给出的解决方案很棒,但检查将在运行时评估。如果你想避免每帧都进行检查,我建议你使用平台相关编译。借助预处理器指令,只有所需的代码才会根据目标平台编译到您的应用程序中

#if UNITY_IOS || UNITY_ANDROID || UNITY_WP_8_1
   for (int i = 0; i < Input.touchCount; ++i)
   {
      if (Input.GetTouch(i).phase == TouchPhase.Began)
      {
         some code here...
      }
   }
#else
   if  (Input.GetKey(KeyCode.RightArrow))
    {
        _normalizedHorizontalSpeed = 1;
    } 
    else if (Input.GetKey(KeyCode.LeftArrow))
    {
        _normalizedHorizontalSpeed = -1;
    }
#endif
Run Code Online (Sandbox Code Playgroud)

但请注意,如果您使用 Unity Remote,此方法会使编辑器中的调试变得更加困难。