Question by
HoneyBadger331 · Mar 28, 2017 at 01:42 PM ·
c#timerspawning
C# - Need help making an enemy spawn timer
What I´m trying to achieve is to set a timer for the enemy spawns. What keeps happening now is that it spawns one cube and after the set time, it starts spawning cubes every single frame.
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawn : MonoBehaviour
{
public GameObject enemyObject;
public float secondsBetweenSpawn;
void Update()
{
if (Time.time > secondsBetweenSpawn)
{
float newEnemySpawnTime = Time.time + secondsBetweenSpawn;
Vector3 spawnPosition = new Vector3 (4.71f, 0.72f, 0f);
GameObject newEnemy = (GameObject)Instantiate(enemyObject, spawnPosition, Quaternion.Euler (0, 0, 0));
}
}
}
Comment
Best Answer
Answer by Deathdefy · Mar 28, 2017 at 02:14 PM
public float secondsBetweenSpawn;
public float elapsedTime = 0.0f;
void Update()
{
elapsedTime += Time.deltaTime;
if (elapsedTime > secondsBetweenSpawn)
{
elapsedTime = 0;
Debug.Log(true);
Vector3 spawnPosition = new Vector3 (4.71f, 0.72f, 0f);
GameObject newEnemy = (GameObject)Instantiate(enemyObject, spawnPosition, Quaternion.Euler (0, 0, 0));
}
}
@HoneyBadger331 please mark it as an answer for others as well. Thanks!