Create an object when another one is clicked C#

I have searched for the solution but I couldn’t find it, and before explaining my problem I gotta say, I’m new using C#, with this I’m not trying to say that I need an easy answer or way of solving the problem, but I could have not solved it because I don’t have a good level of C#.

One solution that I found and I think it’s the correct one is this one:

void Update(){
   if (Input.GetMouseButtonDown(0)){ // if left button pressed...
     Ray ray = camera.ScreenPointToRay(Input.mousePosition);
     RaycastHit hit;
     if (Physics.Raycast(ray, out hit)){
       // the object identified by hit.transform was clicked
       // do whatever you want
     }
   }
 }

(Someone in the comments said it’s hit.collider not .hit)

But I don’t know how to use it. Where he says “// the object identified by hit.transform was clicked” I don’t understand what should I put. I wrote Object.hit.transform but that didn’t mean anything. Can you guys give me an example?

And the other thing is how to create another object. I have read about the command Instantiate, but I can’t create another object. I don’t know if create means literally create, or it means to put into the scene (and that’s what I want).

In resume, I want that if you click an object, another one is created, in the exact position as I want it to be.

Thx for your time, if I explained myself wrongly please tell me and I’ll try to explain it again.

You are not understanding out hit, the out gives you the info about what it hit, like the distance to the hit, the name of the object it hit, the point where it hit, and so on. It can be very helpful in some cases where you wanna know if a laser hit a friendly target or an enemy, for example in your case you want to check tag using hit info.
The hit only detected on the collider not the transform, if you detect hit on the transform or gameObject then null exception will be thrown by the editor.

if (Physics.Raycast(ray, out hit)){
        // the object identified by hit.transform was clicked
        // do whatever you want
if(hit.collider.tag == "ClickableObject") // check by tag  if it hits with the collider
      }

Then You can create new object by using instantiate when you detected hit.

  if (Physics.Raycast(ray, out hit)){
            // the object identified by hit.transform was clicked
            // do whatever you want
    if(hit.collider.tag == "ClickableObject") // check by tag  if it hits with the collider
{
Instantiate(nameOfInstantiatedObject,Position,Rotation)
}
          }

you can create new object in the unity events,when hit detected the invoke unity event and in his listener create new object.

You should learn about prefabs Prefab run time instantiation