Alternate method to restrict actions based off Collision objects name

During the previous lecture I got fairly irritated at the problem solved in this lecture, so I ended up investigating and finding a way to solve the cannon reacting to objects that were not the walls. I used the following piece of code without realizing the possibility of a layer mask inside the Raycast command:

if (Physics.Raycast(ray, out hitInfo)) {
    if (hitInfo.collider.transform.gameObject.name == "ColliderWall") {
        solver.target = hitInfo.point;
    }
}

This method was with it’s flaws however. Whenever you turn towards an object that wasn’t called CollderWall, the cannon would stop rotating. The raycast had already stopped when colliding with the goal or the cannon, and since they did not have the wall’s name, no action was played out. That said, this effect could well make the if command more useful than the layer mask.

Say for example you were creating a first person game, with multiple rooms. In the room next to you lets suppose there was an enemy that turns you to stone when you look directly at it. You don’t want to turn to stone if there is a wall between you and the enemy, even if the camera is pointed directly at the enemy. Attaching the enemy to the wall layer would be inefficient, as it could effect any other scripts you have running based on wall-layer collisions. Instead you would look to create a Raycast that collides with anything, and IF it were to collide with the enemy, then you would turn the player to stone.

Just a post explaining the alternate method of selecting in Raycasting. I have been using this course not as a textbook to pass the exam, but rather as a means to learn the Unity engine. If anyone else happens to pass this, I hope they would find this method useful.

Privacy & Terms