问题
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