Hello!
I really need help with Unity for my uni project. I have chest collectibles that spawn at random spawn points, the problem is that I need only about 15 of them to spawn, but they spawn infinitely. I don’t know how to fix this. Also, maybe somebody knows how to prevent them from overlapping.
Here’s the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameController : MonoBehaviour
{
public int numberRandomPositions = 8;
public int ChestCount = 0;
public GameObject chestPrefab;
public List<Transform> spawnpoints = new List<Transform>();
float chestTimer = 0f;
float minX;
float maxX;
float minY;
float maxY;
void Start()
{
Vector3 viewportBottomLeft = Camera.main.ViewportToWorldPoint(new Vector3(0f, 0f, 0f));
Vector3 viewportTopRight = Camera.main.ViewportToWorldPoint(new Vector3(1f, 1f, 0f));
minX = viewportBottomLeft.x;
maxX = viewportTopRight.x;
minY = viewportBottomLeft.y;
maxY = viewportTopRight.y;
}
// Update is called once per frame
void Update()
{
chestTimer += 1f * Time.deltaTime;
if (chestTimer >= 5f)
{
for (int i = 0; i < 2; i++)
{
int spawnIndex = Random.Range(0, spawnpoints.Count -1);
Instantiate(chestPrefab, spawnpoints[spawnIndex].transform.position, transform.rotation);
}
chestTimer = 0f;
}
}
}