- Home /
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? Thanks in advance.
Answer by tfakgul · Oct 19, 2014 at 02:39 PM
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
}
Answer by bubzy · Oct 19, 2014 at 07:33 AM
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()
{
//your instantiate code here
}
I don't code in JS btw this is my guess at how it looks in JS :D
Your code is true in JS, don't worry :D Btw, this is working fine. And also i noticed that my big mistake is 'i used int variable for PlayerUpdateZ' thanks to you. I changed it to float and ; if (PlayerUpdateZ>(i*40) && PlayerUpdateZ<1+(i*40) ) this code is working.
Thanks your help :)