Too many items spawned

im making a timer and it spawns thousands of bullets here is my code

{
    private const float V = 10f;
    public Rigidbody bullet;
    public Transform EnemySpawner;
    public Transform enemyspawnPoint;
    float timePassed = 0f;
        void Start()
    {
     
    }
    void Update()
    {
            timePassed += Time.deltaTime;
            if(timePassed > 5f)
            {
            Rigidbody bulletInstance = Instantiate(bullet, enemyspawnPoint.position, 
            enemyspawnPoint.rotation) as Rigidbody;
            bulletInstance.AddForce(enemyspawnPoint.forward * 20f);
            }
    }
}

You never reset timePassed.

3 Likes

Avoid accumulating delta time as this accumulates small rounding errors that can add up.

Better style would be to set your target time when something should occur, and compare it against current time.

// fields
private float targetTime;
private float timeThatNeedsToPass = 5f;

// initialize target time
private void RestartTimer()
{
    targetTime = Time.time + timeThatNeedsToPass;
}

// update
if (Time.time >= targetTime)
{
    RestartTimer();
    // do stuff
}
1 Like