Working with Raycast
Challenge: How to instantiate objects using Raycasting
In this small challenge we are going to expand on our knowledge of Raycasting by instantiating a sphere into a floor object whenever we left click.
First we are going to need a new setup for this challenge. We will need a cube that will be turn into a platform and some extras (in my case) a few cylinders to so some elevation.
Next, just like how we created tags for the previous challenge, we will be doing the same for the platform. In this scenario we will be creating a tag called “Floor” which will be assigned to everything including the cylinders.
Since our challenge is to instantiate objects during runtime, we will need to create that object. In this scenario I decided to create a sphere as the instantiated component.
Just to highlight this sphere from the pure white background, I decided to add a new material to the sphere. To finish off the setup, I used this sphere and created a new prefab from it.
Finally we are going to create a new C# script called “spawning” which will then be attached to the Main Camera component.
Repeating what we have done previously, we are going to setup our script to use the New Input System (so we need to access the Input Library). Since we need to instantiate the sphere prefab we will need access to the game object, therefore we can use a serialized field to drop in the slot.
Next we are going to use the process to trigger the raycast using the new input system. We are going to use the ray cast origin from the mouse position and store the Raycast hit info as the hitInfo variable.
Next we will do the standard Physics Raycast IF statement, and also creating a new variable called hitObject and store the hitInfo collider data.
We will also need to do a Null check to make sure the the hitObject is functioning properly, if not we do a return function.
Finally to instantiate the sphere prefabs, we will need to first do an tag check to see if the mouse cursor is over the Floor and any object with the tag assigned to “Floor”. And to instantiate to the location of the raycast we have something called “point” which serves as a vector3 variable. As stated by the Unity API, point is the impact point in world space where the ray hit the collider.
Once that is completed we are going to save our script and head back to Unity. There can drag the sphere prefab into the open slot in the script that is attached to the Main camera. Now when playing during runtime, whenever the mouse cursor is over the floor and objects, you are able to instantiate the red sphere prefab.