Reputation: 93
I seek a way to handle touches that do not start on UI elements in Unity Engine.
The purpose of this is rotating, panning and zooming in on a "map" (it shall be called so from now on). But if the touch down event is on any of the UI elements it shall be handled by that UI element instead of the map.
I think one such example is Google's Maps android application.
I have tried several solutions:
Mouse events - but this combines all of the touches into a single one
Input.touches - but I do not know how to find out if the touch should be handled by another UI element instead (I would like if possible to not use "if"s to check if the touch is on any another UI element as this might prove a real performance issue)
Upvotes: 2
Views: 1378
Reputation: 125455
I seek a way to handle touches that do not start on UI elements in Unity Engine ...But if the touch down event is on any of the UI elements it shall be handled by that UI element instead of the map.
The IsPointerOverGameObject
function is used to simplify this. If it returns false, do you panning, rotation. If it returns true then the mouse is over any UI element. It is better and easier to use this than to use a boolean variable that is modifed by every UI element. Use OnPointerClick
to detect events on the UI(map). See this for more information.
void Update()
{
checkTouchOnScreen();
}
void checkTouchOnScreen()
{
#if UNITY_IOS || UNITY_ANDROID || UNITY_TVOS
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
//Make sure finger is NOT over a UI element
if (!EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
{
OnSCreenTouched();
}
}
#else
// Check if the left mouse button was clicked
if (Input.GetMouseButtonDown(0))
{
//Make sure finger is NOT over a UI element
if (!EventSystem.current.IsPointerOverGameObject())
{
OnSCreenTouched();
}
}
#endif
}
void OnSCreenTouched()
{
Debug.Log("Touched on the Screen where there is no UI");
//Rotate/Pan/Zoom the camera here
}
I would like if possible to not use "if"s to check if the touch is on any another UI element as this might prove a real performance issue
There is no other way to do this without an if
statement. Even the simple answer above requires it. It doesn't affect the performance.
Upvotes: 2