Spawning to many gameObjects?

I'm making a basic 'dodge the obstacle' game (I'm an absolute beginner) and so far I've coded the player and obstacle, but trying to get the obstacle to spawn I end up spawning far too many and I'm not sure what I'm doing wrong. They're spawning in random positions like I want, but not in the quantity I need. Any suggestions, thanks :)

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

public class spikeLogic : MonoBehaviour
{
    public BoxCollider2D grid;
    public GameObject spike;

    private float timeUntilSpawn;
    [SerializeField] private float minSpawnTime;
    [SerializeField] private float maxSpawnTime;

    // Start is called before the first frame update
    void Start()
    {
        RandomizePosition();
    }

    // Update is called once per frame
    void Update()
    {
        if (timeUntilSpawn <= 0)
        {
            Instantiate(spike);
            SetTimeUntilSpwan();
        }
    }

    private void RandomizePosition()
    {
        Bounds bounds = this.grid.bounds;

        float x = Random.Range(bounds.min.x, bounds.max.x);
        float y = Random.Range(bounds.min.y, bounds.max.y);

        this.transform.position = new Vector3(Mathf.Round(x), Mathf.Round(y), 0.0f);


    }

    private void SetTimeUntilSpwan()
    {
        timeUntilSpawn = Random.Range(minSpawnTime, maxSpawnTime);
    }


void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground")
            Destroy(gameObject);
        if (collision.gameObject.tag == "Player")
            Destroy(gameObject);
            //Destroy(collision.gameObject);
    }
}

9817065--1410759--Screenshot 2024-05-06 124422.png

Where are you decreasing timeUntilSpawn?
You gotta subtract Time.deltaTime from it in the update event.

1 Like

Debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

https://docs.unity3d.com/Manual/ManagedCodeDebugging.html

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log() to find out if any of your code is even running. Don't assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

And yes, as @DragonCoder suggests, answer those questions. :)

I also suggest improving your naming, such as with spike. Is that a prefab? Is that the instantiated one? Who knows. Name it spikePrefab, and if you need to keep a copy after it is instantiated, name that a separate variable called spikeInstance

1 Like