How to detect if unity game is running on (web keyboard) or (mobile touch)

房东的猫 提交于 2019-12-11 08:20:03

问题


basically, I have a unity game supported by physical keyboards and touch screens in mobile devices. I already finished my movement script for physical keyboards, and now, I'm coding for touch screens.

How can I achieve that detect feature?

I was thinking something like that...

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...
          }
       }
   }
}

Appreciate


回答1:


The solution given by @ryemoss is great, but the checks will be evaluated at runtime. If you want to avoid the checks every frames, I advise you to use Platform dependent compilation. Thanks to preprocessor directives, only the desired code will be compiled into your application according to the targeted platform

#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

However, note that this method makes harder to debug in the editor if you use Unity Remote.




回答2:


You are looking for Application.platform. Something like the following should achieve what you are looking for or read here for more devices.

if (Application.platform == RuntimePlatform.WindowsPlayer)
    Debug.Log("Do something special here");
else if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
    Debug.Log("Do something else here");

However, you may be better off getting rid of this check all together since it is redundant! If you are pressing the right or left arrow you already know the user is using a keyboard.



来源:https://stackoverflow.com/questions/44961076/how-to-detect-if-unity-game-is-running-on-web-keyboard-or-mobile-touch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!