Working with Raycast

Challenge: Raycasting with Multiple Objects

Simon Truong
3 min readFeb 3, 2023

--

Now that we have a simple understanding on how raycasting works, and we have a functional system which changes color when left mouse clicking on a 3D cube, it is time to push the concept further. In this challenge we will add in more than just 3D cubes, we will add in a sphere and a capsule object. We want to only limit the random color change to the cubes only, and the sphere should not be affected. As for the Capsule, we only want the color to change once to black.

Starting the challenge:

First we need to setup the scene properly, I will create 2 more 3D cubes and 1 sphere and capsule.

Other than the given name, there is no other way to currently identify them, therefore we will need to add in tags to group them under one hierarchy. I defined 3 tags (cube, sphere and capsule) and assigned each shape to the corresponding tag.

Scripting:

Since this an expansion on the previous challenge we are going to be using the same script as before.

The setup has been already been written previously, but we are just going to expand its function with the newly created tags. The easily way to identify tags to do the same function is via “Switch statements”. Since we are just swamping different tags, this should be easy to implement.

Inside the raycast method, we are going to use the hit Object variable, but this time we are going to check if it is null, and when it does equal to null we will do a null return function.

On the switch statement, we are basically going to give each tag a case logic.

Make sure that the name of the tag must match the switch case name, this includes capital letters.

As you can read from the script, we are limiting the random color swap to just the cubes, and only swapping to black color on the capsule. The sphere is left to do nothing.

--

--

Simon Truong

A Designer, an Illustrator and a massive tech geek aspiring to become a professional Unity Developer.