How to Instantiate a prefab onto a grid?

Dear UnityAnswers community,

I’ve looted a bit of code from someone else to help facilitate a little dungeon creator I’m working on. The code is placed in the main player camera and it spawns a little cube when the player clicks on the mouse.


var building : GameObject;
var gridX = 5;
var gridY = 5;
var spacing = 2.0;
function Update () 
function Build()
        var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        var hit : RaycastHit;
        if (Physics.Raycast (ray, hit, 100)) 
            Debug.DrawLine (ray.origin, hit.point);

What I need to work out is how best to get the cube to follow some kind of grid and only create a new prefab along certain X-Y-Z axis!

May I point out that this isn’t going to be a MineCraft clone- I’m simply using the cube as a starting point and will actually replace this with in game prefabs such as walls, doors, etc… However, I suppose the principal is the same although the objects I have in mind may be several blocks high/long/wide for certain ‘props’.

Thanks in advance

Suppose the grid is 5x5 squares. That means you want to snap to center points of 2.5, 7.5, 12.5 … . First compute the grid square you are on, then scale for size, then center it.

You currently instantiate at the hit.point:

Instantiate(explosionPrefab, hit.point, rot);

Instead, recompute the grid center near hit.point and spawn there:

float3 P = hit.point;
P.x = Mathf.Floor(P.x/5) * 5 + 2.5f;
// same for z
// If your ground isn't flat, look up P.y = groundHT at x,z
// If you might be on a rock, do a new raycast down from P to get new HT/normal

// spawn using corrected point:
Instantiate(explosionPrefab, P, Quaternion.identity);

If you camera is always aimed straight down, you could probably do the math early, after screenPointToRay, to avoid the 2nd raycast.