Help needed with spawning objects at the right location

Hi
I’m trying to make a snake game. When the snake collides with one of the dots I want it to spawn a new segment behind the last segment of the snake. So I want the distance that the new segment spawns behind the snakes head becomes one less every time a new tailsegment spawns. With my code a segment spawns when the snake collides with a dot but it doesn’t spawn in the right place. All segments spawns in a circle around the snake depending on wich direction it’s facing when it collides. The distance behind the snake the segments spawn doesn’t get any bigger either, it just stays at 1. This is my code.

#pragma strict

function Start () {

}
var zaxis : int;
var tailendlocation : Vector3;     
var tailsegment : GameObject;


function OnCollisionEnter(collision : Collision){
if(collision.gameObject.tag == "dot"){

Debug.Log("spawn");

var zaxis : int = zaxis+1;

var tailendlocation = Vector3(transform.position.x, transform.position.y, transform.position.z - zaxis);


var Instance : GameObject = Instantiate(tailsegment, tailendlocation, transform.rotation);
Instance.transform.parent = transform;


}}

I think that I have made something wrong when i wrote this
transform.position.z - zaxis

I would appreciate if someone could help me.

You’ve got the right idea but the wrong implementation.
You do want the z axis, but you’re implementing it via the z component of the position vector.
You want to use transform.forward to get the z axis (a complete directional vector), then offset from your snake head with: transform.Foward * -sizeOfSegment. (-ve as we want a backwards offset).