Objective: Use Raycast to place an object down.
Today we will look into spawning objects at the place of mouse click. To get started I created a cube and stretched it out to make a floor.
I also added a tag of Floor to the floor.
Next I created a Sphere and made a prefab out of it by dragging it into the project window.
Now it’s time to get in to the script. Create a C# script and grab Unity’s Input system.
I added a Gameobject reference to hold the Sphere prefab we made earlier.
In Update it’s time to grab the input from the left button of the mouse. Inside this check we will create a RaycastHit variable, grab the mouse position, and finally create a Ray with the mouse position as the vector3 for ScreenPointToRay.
Once we get that, we will see if the Physics.Raycast hits anything. If the Ray hits anything, it will return the name of what it hits.
Now that the ray can hit something and return information, we will check to see if what we hit was the floor and if it was Instantiate an object at the point by using hitInfo.point.
Using this system we can spawn an object on another object in the scene. Thank you for reading and have a wonderful day.