- Home /
How can I stop prefabs from spawning after a certain number of game objects, with specific tags has been reached?
using System.Collections; using UnityEngine;
public class PrefabSpawner : MonoBehaviour { public GameObject[] prefabs; public Vector3 spawnValues; public float spawnWait; public float spawnMostWait; public float spawnLeastWait; public int startWait; public bool stop; int randPrefab;
void Start()
{
StartCoroutine(waitSpawner());
}
void Update()
{
spawnWait = Random.Range(spawnLeastWait, spawnMostWait);
}
IEnumerator waitSpawner()
{
yield return new WaitForSeconds (startWait);
while (!stop)
{
randPrefab = Random.Range(0, 9);
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), 1, Random.Range(-spawnValues.z, spawnValues.z));
Instantiate(prefabs[randPrefab], spawnPosition + transform.TransformPoint(0, 0, 0), Random.rotation);
yield return new WaitForSeconds(spawnWait);
}
}
}
Answer by tormentoarmagedoom · Oct 18, 2018 at 08:17 AM
Good day.
You need to check the number of objects in the scene with a specifyc tag? Use this:
if (GameObject.FindObjectsWithTag("TheTag").length < 10)
{
Spawn another object;
}
else
{
Do not spawn more objects;
}
So you are creating an array with all objects with tag "TheTag" and checking if its lenght is more or less than 10.
Bye!
Your answer
Follow this Question
Related Questions
2D Tilemap Gameobject Brush Script for Editor 0 Answers
noobHell, prefab arrays, GameObjects, Random Spawning 1 Answer
Client's list of game object prefabs not shown in the Server. How do I solve this? 0 Answers
Create multiple prefabs from multiple objects in the selection of the Hierarchy (Unity 5.3.5) 1 Answer
How to talk about objects in the scene, not prefabs? 0 Answers