How to prevent touch going through UI in Unity?
Methode - 1 :
To prevent touch from going through a UI in Unity, you can enable the "Raycast Target" option for the UI elements that you want to prevent touch from passing through. This will cause Unity to cast a ray from the touch position and detect if it hits any UI elements with the "Raycast Target" option enabled. If it does, the touch will be registered on the UI element and will not pass through to any other elements behind it.
Here's how you can enable the "Raycast Target" option for a UI element in Unity:
- In the Hierarchy, select the UI element that you want to prevent touch from passing through.
- In the Inspector, locate the "Image" component for the UI element.
- Under the "Image" component, check the box next to the "Raycast Target" option.
- The UI element will now prevent touch from passing through it.
Note: This solution will only work if you are using Unity's built-in UI system. If you are using a different UI system, the steps to prevent touch from passing through a UI element may be different.
Methode - 2 :
There are several ways to prevent touch from going through UI in Unity:
Use a Canvas Group component on the UI element and set the Interactable and Blocks Raycasts properties to true. This will prevent the UI element from receiving touch input when it is overlapped by other UI elements.
Use a Raycast Target component on the UI element and set the Raycast Target property to true. This will cause Unity to ignore any touch input that hits the UI element, preventing it from passing through to the underlying objects.
Use a Graphic Raycaster component on the parent canvas of the UI element. This will enable Unity to detect touch input on the UI element and prevent it from going through to the underlying objects.
Use a Layer Mask on the Graphic Raycaster component to exclude certain layers from receiving touch input. This can be useful if you have multiple canvases in your scene and want to prevent touch input from going through to certain objects.
Use a Canvas Scaler component on the parent canvas of the UI element and set the Screen Match Mode property to "Match Width or Height". This will cause the UI element to scale with the screen size, preventing it from being overlapped by other UI elements and blocking touch input from going through.
