Asteroid SpawnRate Issue

Hi there
I dont know why I have low spawn rate hir is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AsteroidSpawner : MonoBehaviour
{
public GameObject asteroidPrefabs;
public float secondsBetweenAsteroids = 1.5f;
public Vector2 forceRange;

float timer;
Camera mainCamera;

void Start()
{
    mainCamera = Camera.main;
}

// Update is called once per frame
void Update()
{
    timer -= Time.deltaTime;
    if (timer <= 0)
    {
        SpawnSateroid();
        timer += secondsBetweenAsteroids;
    }
}

private void SpawnSateroid()
{
    int side = Random.Range(0,4);

    Vector2 spawnPoint = Vector2.zero;
    Vector2 direction = Vector2.zero;

    switch (side)
    {
        case 0:
            spawnPoint.x = 0;
            spawnPoint.y = Random.value;
            direction = new Vector2(1f, Random.Range(-1, 1));
            break;
        case 1:
            spawnPoint.x = 1;
            spawnPoint.y = Random.value;
            direction = new Vector2(-1, Random.Range(-1, 1));
            break;
        case 2:
            spawnPoint.x = Random.value;
            spawnPoint.y = 0;
            direction = new Vector2(Random.Range(-1, 1), 1f);
            break;
        case 3:
            spawnPoint.x = Random.value;
            spawnPoint.y = 1;
            direction = new Vector2(Random.Range(-1, 1),-1);
            break;
    }

    Vector3 worldSpawnPoint = mainCamera.ViewportToWorldPoint(spawnPoint);
    worldSpawnPoint.z = 0;

    GameObject selectedAsteroid = asteroidPrefabs[Random.Range(0, asteroidPrefabs.Length)];
    Quaternion asteroidRotation = Quaternion.Euler(0, 0, Random.Range(0, 360));
    GameObject asteroidInstance = Instantiate(selectedAsteroid, worldSpawnPoint, asteroidRotation);

    Rigidbody asteroidRb = asteroidInstance.GetComponent<Rigidbody>();
    asteroidRb.velocity = direction.normalized * Random.Range(forceRange.x, forceRange.y);
}

}

its the same as lecture
it doesnt spawn more then three asteriod on screen

I well be grateful to anyone can help and explain why that happen.

According to the heirarchy, the correct number of asteroids seem to be spawned. It is possible they are just flying off the screen due to randomized vectors.

Try double clicking them and watching them in the scene view.

edit: They might be easier to debug if you give them trail renderers.

1 Like

thank you

your idea helped me alot

it seem solved when i just decrease the delay Between asteroids a little

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms