50 lines
1.4 KiB
C#
50 lines
1.4 KiB
C#
using UnityEngine;
|
|
|
|
public class CartSpawner : MonoBehaviour
|
|
{
|
|
public GameObject cartPrefab;
|
|
public Vector3 spawnAreaCenter;
|
|
public Vector3 spawnAreaSize;
|
|
public float spawnInterval = 10f; // Time (seconds) between spawns
|
|
public int maxCartsInScene = 5; // Prevent too many carts
|
|
|
|
private int currentCarts = 0;
|
|
|
|
void Start()
|
|
{
|
|
StartCoroutine(SpawnCartsOverTime());
|
|
}
|
|
|
|
System.Collections.IEnumerator SpawnCartsOverTime()
|
|
{
|
|
while (true)
|
|
{
|
|
if (currentCarts < maxCartsInScene)
|
|
{
|
|
Vector3 spawnPosition = GetRandomPositionInArea();
|
|
GameObject newCart = Instantiate(cartPrefab, spawnPosition, Quaternion.identity);
|
|
currentCarts++;
|
|
|
|
// When cart is returned/destroyed, decrement the counter
|
|
CartTracker tracker = newCart.AddComponent<CartTracker>();
|
|
tracker.spawner = this;
|
|
}
|
|
|
|
yield return new WaitForSeconds(spawnInterval);
|
|
}
|
|
}
|
|
|
|
Vector3 GetRandomPositionInArea()
|
|
{
|
|
float x = Random.Range(-spawnAreaSize.x / 2, spawnAreaSize.x / 2);
|
|
float z = Random.Range(-spawnAreaSize.z / 2, spawnAreaSize.z / 2);
|
|
float y = spawnAreaCenter.y;
|
|
|
|
return spawnAreaCenter + new Vector3(x, 0f, z);
|
|
}
|
|
|
|
public void CartRemoved()
|
|
{
|
|
currentCarts--;
|
|
}
|
|
}
|