So I am tryng to make a game in unity using C# code, now...I have a cube that jumps on pylons... It's an infinite runner game.
The problem is that I want to spawn the pylons based on the distance that the cube has traveled...
Let say that the cube has traveled 12 meters, I want to spawn a new pilon every time the cub has traveled that distance, so it traveled 12 meters, spawn a new pylon, it traveled another 12 meters, spawn a new pylon and so on...
I want to make the cub travel faster and faster so that why I need to know the distance at which the pylons need to spawn.
I tried to use the functions Instantiate()
, and used an if statement looking for transform.position.z
of the cube..
The real problem is that every time the cube has traveled 12 meters and is time to instantiate a new pylon, it spawns like 20 pylons because I use this in update function , and it sees the position as a float , instantiating the the full number, 12,1 ; 12,2 ; 12,3 ; 13,4 ... until ; 12,99 ... I want to know how can I spawn the pylon only once.
Also...if you have a better solution for spawning the pylons please show me.
This is the code that I used to spawn the pylons ,respectively the functions that I used.
Some of this are the variables that I used.
public float cameraSpeed = 1;
public float horizontalSpeed;
private int spawnIndex;
public float spawnDistance;
private int[] prevPoints;
public GameObject[] pilon;
public GameObject spawnMainPoint;
public Transform[] spawnPoints;
public Transform[] coinsSpawnPoint;
public float enamySpeed;
private int currentPoint;
public Transform[] pointPosition;
void FixedUpdate () {
int currPosition = (int)transform.position.z;
if (currPosition % spawnDistance == 0f) {
SpawnCoinPylon ();
SpawnNormalPylon ();
}
void SpawnNormalPylon ()
{
spawnIndex = Random.Range (0, spawnPoints.Length);
Instantiate (pilon[0], spawnPoints [spawnIndex].position,spawnPoints [spawnIndex] .rotation);
}
void SpawnCoinPylon(){
Instantiate (pilon[1], coinsSpawnPoint [0].position,spawnPoints [spawnIndex] .rotation);
}
Thank you!
UPDATE :
I managed to pull it of , here is the correctly working code:
private int currPosition ;
void Start () {
currPosition = (int) transform.position.z;
}
void FixedUpdate () {
bool hasSpawnedPylon = false;
if (currPosition != (int)transform.position.z) {
if ((int)transform.position.z % spawnDistance == 1) {
if (!hasSpawnedPylon) {
SpawnCoinPylon ();
SpawnNormalPylon ();
currPosition = (int)transform.position.z;
}
}
}
else
{
hasSpawnedPylon = false;
}
}
void SpawnNormalPylon ()
{
spawnIndex = Random.Range (0, spawnPoints.Length);
Instantiate (pilon[0], spawnPoints [spawnIndex].position,spawnPoints [spawnIndex] .rotation);
}
void SpawnCoinPylon(){
Instantiate (pilon[1], coinsSpawnPoint [0].position,spawnPoints [spawnIndex] .rotation);
}