Raycasting: Click to Instantiate

Thomas Mauro
3 min readDec 27, 2022

--

In this article, I will go through the basics of instantiating an object in Unity with the click of the mouse. Let's get right into it, shall we?

What I will do here is make it so that when I click on the floor (cube) an object will instantiate.

  • Add a cube, set the to position 0,0,0, and the scale to 10,0.01,10 and -90 on the X/Rotaion (Alternatively you can just keep the Y scale at 1)
  • Add a sphere to the scene and make it a Prefab
  • Make a new material for the sphere to give it a new color (I called it Sphereterial and colored it dark red and made it metallic and gave it smoothness.)
  • Make a Player.cs (Script) and put it on the Floor
  • Initialize using UnityEngine.InputSytem;
  • Make a Variable for a prefab to instantiate
  • In the Update method I need some code for:

//if left click

//raycast (origin = mouse pos)

//hitInfo (to detect the floor)

//instantiate sphere at the hit point

The only thing left to do is test it out to see it in action.

We aren't out of the woods just yet. Let's spice this up a bit. I want to add other shapes (prefabs) to instantiate at random with a random color. They will all have their own color and when I click the floor a random shape will instantiate. I won't go into much detail. Here is the code and here it is working.

--

--