59 lines
1.4 KiB
C#
59 lines
1.4 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using Managers;
|
|
using Unity.Mathematics;
|
|
using UnityEngine;
|
|
|
|
public class CollectibleSpawner : MonoBehaviour
|
|
{
|
|
public float SpawnSphereRadius = 1.5f;
|
|
public float SecondsTillNextSpawn = 10;
|
|
public int MaxSpawnedObjects = 4;
|
|
public List<GameObject> Spawnables;
|
|
|
|
private List<GameObject> spawnedObjects = new();
|
|
private float secondsSinceLastSpawn = 0;
|
|
// Start is called before the first frame update
|
|
void SpawnRandom()
|
|
{
|
|
int index = UnityEngine.Random.Range(0, Spawnables.Count);
|
|
int angle = UnityEngine.Random.Range(0, 360);
|
|
Vector3 spawnPosition = new Vector3(math.cos(angle), math.sin(angle), 0);
|
|
spawnPosition *= SpawnSphereRadius;
|
|
SpawnCollectible(index, spawnPosition);
|
|
}
|
|
|
|
private void SpawnCollectible(int spawnableIndex, Vector3 spawnPosition)
|
|
{
|
|
var spawned = Instantiate(Spawnables[spawnableIndex]);
|
|
spawned.transform.SetParent(transform);
|
|
spawned.transform.localPosition = spawnPosition;
|
|
spawnedObjects.Add(spawned);
|
|
UIManager.G.OffScreenManager.AddTarget(spawned);
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
for (int i = 0; i < spawnedObjects.Count; ++i)
|
|
{
|
|
if (!spawnedObjects[i].activeSelf)
|
|
{
|
|
Destroy(spawnedObjects[i]);
|
|
spawnedObjects.RemoveAt(i);
|
|
}
|
|
}
|
|
if (spawnedObjects.Count < MaxSpawnedObjects)
|
|
{
|
|
secondsSinceLastSpawn += Time.deltaTime;
|
|
}
|
|
if (secondsSinceLastSpawn > SecondsTillNextSpawn)
|
|
{
|
|
secondsSinceLastSpawn = 0;
|
|
SpawnRandom();
|
|
}
|
|
}
|
|
|
|
|
|
|
|
}
|