Player's gun go through all object in the game

Player have a gun, which is Player’s child object. When he moves too close to any object, the gun go through it. How can I solve it?

Brackeys made a very good video about this some time ago. You can check it out here.

But basically you need two cameras. Parent the “weapon camera” to the main camera of your player. Remove all the components except the camera component from the weapon camera. Now on the camera component of the weapon camera, change the Depth to 1 and the Clear Flags to Depth Only. Now create a layer or use an old one and assign that layer to your gun. On the main camera of the player, in the culling mask, uncheck the layer the gun is on. Now on the weapon camera, on culling mask, uncheck everything except the layer the gun is on.

But please be aware of this! The gun will still go through the level but the player won’t be able to see it! And if you have your shoot position in the gun, the player may be able to shoot through the wall if it is thin enough!

I hope this helped you!

One solution (maybe not the best one, but still common) is to create a second camera, which render only the weapon, and change it to render before the game’s main camera. I’ve seen this solution from old to new games.