Random.Range Issues [Java]

I’ve been following a beginner’s course to Unity and I’ve run into a problem.

function Update ()
{
	if (Input.GetMouseButtonDown(0))
	{
		print ("Left Click");
		var hit : RaycastHit;
		var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		if (Physics.Raycast(ray, hit, 100.0))
		{
			if (hit.transform.tag == "enemy");
			{
				var position = Vector3 (Random.Range(-2, 2),Random.Range(-5, 5), 0);
				hit.transform.position = position;
				print ("You hit an object!");
			}
		}
	}
}

It should randomly move the position of the object between any of those numbers, but not move it forwards/backwards at all, yet it does.

It’s overwriting z, which I am not sure you want it to do.

Try setting the new positions z to the old positions z.

var z = hit.transform.position.z;
var position = Vector3 (Random.Range(-2, 2),Random.Range(-5, 5), z);
hit.transform.position = position;

Another possible solution would be to increment x and y instead of overwriting them.

var position = Vector3 (Random.Range(-2, 2),Random.Range(-5, 5), 0);
hit.transform.position = hit.transform.position + position;