so my code works when it comes to spawning an enemy except because its in the update function its happening to fast how do i fix this?
here is my code
public GameObject enemySpawner;
public GameObject enemy;
public float maxTime = 5;
public float middleTime = 3.5f;
public float minTime = 0;
private float time;
private float spawnTime;
// Use this for initialization
void Start () {
SetRandomTime();
time = minTime;
}
void SetRandomTime()
{
spawnTime = Random.Range(minTime, maxTime);
}
// Update is called once per frame
void Update () {
if (middleTime >= spawnTime)
{
Debug.Log(time + spawnTime);
SpawnEnemy();
SetRandomTime();
}
else if (time != spawnTime)
{
Debug.Log(time + spawnTime);
SetRandomTime();
}
}
private void SpawnEnemy()
{
GameObject Temporary_enemy_Handler;
Temporary_enemy_Handler = Instantiate(enemy, enemySpawner.transform.position, enemySpawner.transform.rotation) as GameObject;
enemySpawner.transform.Rotate(Vector3.left * 90);
}
The issue is that the update method is called every frame, so the speed at which anything happens inside is determined by how fast your computer runs the program unless you use Time.deltaTime.
I would recommend using a simple countdown timer instead of using the probability of the spawnTime variable to be greater than middleTime.
Something like this would work.
float targetTime = 5.0f; //how long it will count down
void Update()
{
targetTime -= Time.deltaTime; //reduce target time by 1 every second
if (targetTime <= 0.0f) //timer ended
{
targetTime = 5.0;
timerEnded();
}
}
void timerEnded() //create your enemy
{
GameObject Temporary_enemy_Handler;
Temporary_enemy_Handler = Instantiate(enemy, enemySpawner.transform.position, enemySpawner.transform.rotation) as GameObject;
enemySpawner.transform.Rotate(Vector3.left * 90);
}
This code spawns an enemy every 5 seconds, you can make that shorter by reducing the targetTime value. Also, look at where Time.deltaTime is used, basically it functions as a real world clock as it records the actual time in-between frames, you should definitely research it some.
Also if you want to add some randomness to your spawning still, you can add some code when you initialize targetTime and when you reset it when it reaches zero.
Something like what you had…
float minTime = 1.0f;
float maxTime = 5.0f;
if (targetTime <= 0.0f)
{
targetTime = Random.Range(minTime, maxTime);
timerEnded(); //timer ended
}