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);
}
}
