SCRIPTING LANGUAGE: C#
I am a Unity beginner and I was making a 3D game where the objective is to shoot and destroy cubes. Everything seems to be working so far, but is there a way to check if the Raycast is not hitting the terrain? The gun uses Raycasting to destroy the object in the center of the screen, but if it points at the ground, it destroys the terrain. How can I prevent this?
Usually one uses different ways of doing this then checking if it’s just not the terrain. Mainly because 1) that Find call is slowish, and 2) what if you start adding more objects that can’t be destroyed?
Method you can consider
Layers/Tags - you can tag your destructable objects, or put them on a destructable layer. Then you just check the respective property of the gameObject, and if it’s on the correct layer you destroy it.
Destructable Component - (this is the method I use personally), create a component describing a destructable. When you hit an object attempt to grab the Destructable component from it. If the component doesn’t exist or isn’t enabled… then it’s not destructable. If it does exist and is enabled… destroy it. The Destructable component can also be used to store health information, item drop code, and other stuff to describe the destructable even more.