Spawning an object on a grid

Hello, I am trying to spawn an object on left mouse click, and this object has to constrained to a grid. So far, it spawns in a grid, but they only spawn in a diagonal line. I tracked this down the the Mathf.Round function, because every object spawned has the same x and z co-ordinates, (5,5 / 4,4 / 3,3) and thats whats causing it to spawn in a diagonal line.

This code goes on my camera:

var gridSize : float = 1.0;
var prefab : GameObject;
var clone : Transform;
function Update () {
    if (Input.GetMouseButtonDown(0)) {
        // Construct a ray from the current mouse coordinates
        var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        var hit : RaycastHit;
        
            if (Physics.Raycast (ray, hit)) {
            // Create a particle if hit
            clone = Instantiate (prefab, hit.point, transform.rotation).transform;
        }
    }
}

This code goes on the spawnable object:

#pragma strict

var gridSize : float = 1;

function Start () {
    transform.position.x = Mathf.Round(transform.position.x / gridSize) * gridSize;
	transform.position.y = Mathf.Round(transform.position.y / gridSize) * gridSize;
    transform.position.z = Mathf.Round(transform.position.x / gridSize) * gridSize;
}

Help?

Ok, so I am trying to do it a different way. I have created a grid of many different planes, and I am using the planes as my grid.

Code:

#pragma strict

var open_tag : String;
var closed_tag : String;
private var open_grid : GameObject[];

function Start()
{

}

function Update()
{
open_grid = GameObject.FindGameObjectsWithTag (open_tag);
var hit : RaycastHit;
var mousePos : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);

	if(Physics.Raycast(mousePos)  hit.collider.tag == open_tag  Input.GetMouseButtonDown(0))
	{
		Debug.Log("YESS!");
	}
}

//            if (hitinfo.transform.tag == "Dirt")

Yet now, I am getting ‘Object reference not set to a an instance of an object’ error, on line 18. Halp?

hit probably equals nil

try this:

if (Physics.Raycast(mousePos, hit, 100)  hit.collider.tag == open_tag  Input.GetMouseButtonDown(0))
{
  Debug.Log('YESS!");
}

In this way the value of hit gets assigned during the raycast

Ok, that fixed it, thanks dterbeest.

What was wrong was that I had not define ‘hit’ in my ray declaration.