# Instantiate only one Prefab per 40 unit

Hello,
I have a player and enemies. I am trying to do this:

‘When the player moved 40 units in z axis, instantiate only one enemy’

My code:

``````PlayerUpdateZ=transform.position.z;
var iSayi:float= Mathf.FloorToInt( (PlayerUpdateZ/40);

for (var i : int = 0;i < iSayi; i++) {
if (PlayerUpdateZ>(i*40) && PlayerUpdateZ<(i+1)*40))
{
var enemy : GameObject = Instantiate(prefab,Vector3(0,0,SpawnPointZ),Quaternion.identity);
}

}
``````

This code instantiates too many objects when player’s position is between 0-40, 40-80 …

If i change the code like this, When the player speed up, unity doesn’t detect every unit in z axis. So sometimes there is not any change when PlayerUpdateZ=40 or 80 or 120…

`````` if (PlayerUpdateZ==(i*40))
{
var enemy : GameObject = Instantiate(prefab,Vector3(0,0,SpawnPointZ),Quaternion.identity);
}
``````

How can i do this?

assuming that the player only moves forward on the z axis:

``````var oldZ : float;
var unitsMoved : float;

function Start()
{
oldZ = transform.position.z;
}

function Update()
{
if(transform.position.z != oldZ)
{
unitsMoved += transform.position.z - oldZ;
}
if(unitsMoved >=40)
{
makeEnemy();
}

}

function makeEnemy()
{
}
``````

I don’t code in JS btw this is my guess at how it looks in JS

Indeed, i could’t work your code. I made some changes in the code and it’s working :

`````` var oldZ : float;
var unitsMoved : float;
var PlayerUpdateZ : float;

function Start()
{
oldZ = transform.position.z;
}
function Update ()
{
PlayerUpdateZ=transform.position.z;
unitsMoved = PlayerUpdateZ-oldZ;
if(unitsMoved >=40)
{makeEnemy();
BusZ=PlayerUpdateZ;}
}
function makeEnemy()
{
//Instantiate here
}
``````