Spawning Prefab


I just have this quick question about spawning prefabs, and I hope someone could please give me an example code that hopefully can do what I want to be done in my game!

What do I want to do?

  • I want to spawn object like in Minecraft (please dont direct me to the minecraft starter package), when you right click an object. I have been able to spawn prefabs already, but I dont know how to make it spawn depending og where on the object you click.


  • You have this cube in your world, and if you right click on the top of it, it will spawn the prefab simply on top of it. If you click on the side, it will spawn on that side of the object. Each object is 1 by 1 by 1 in radius, which means the object only takes 1 by 1 by 1 location on the map, so its not that hard to figure out what location the prefab is going to spawn, I just dont know how to code it…

This is my code so far in the script;

			Instantiate(myGameobject, new Vector3(10, 10, 10), Quaternion.identity);

I hope someone can help me whit this,

Best Regards,

Marius AW

Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hitinfo = new RaycastHit();
if (Physics.Raycast (ray, out hitinfo, 100)) {
// Next line uncommented to generate object where clicked
Instantiate(myGameobject, hitinfo.point, Quaternion.identity);
// Next line uncommented to generate object in cube where clicked
//Instantiate(myGameobject, new Vector3((int) hitinfo.point.x, (int) hitinfo.point.y, (int) hitinfo.point.z), Quaternion.identity);

Oh, just to inform you: I’m working on something similar to your idea too…

EDIT: Fixed!