Unity

How to block raycasts with Unity UI elements

While testing a new feature in an unannounced game I’m working on, I noticed some confusing behaviour in Unity: if a Screen Space UI element (such as a button) was hovering over a 3D model in the game, clicking on the UI button would work as expected, but the model under the button was also reacting as though it had been clicked on. This was obviously not the behaviour I wanted.

I went searching for a solution to this problem, and I couldn’t find a simple explanation of how to solve it anywhere, so once I figured out how to solve the problem I figured I should write out what I’ve learned so that anyone else encountering the same problem could save some time. This code was tested in Unity 2021.3, but should work in other versions.