How to make Object X spawn when there're no more Objects tagged "XYZ" in scene?
Hey there, I'm trying to come up with a simple script that basically searches for objects in the current scene that are given a certain tag. If those objects still exist, the script continues simply repeats the search...and carries on for eternity until there the tagged objects are all gone. And then the script says "Oh, now I activate my prefab." Any ideas on how to do this in a very flexible way?
Answer by Xarbrough · Jun 07, 2016 at 11:03 PM
Try this:
public string searchTag = "MyTag";
public GameObject prefab;
IEnumerator Start()
{
while (true)
{
var taggedObjects = GameObject.FindGameObjectsWithTag(searchTag);
if (taggedObjects.Length < 1)
{
ActivatePrefab();
yield break;
}
yield return new WaitForSeconds(1f);
}
}
void ActivatePrefab()
{
var instance = Instantiate(prefab);
instance.SetActive(true); // if it isn't already.
}
Basically, you want to search for all objects with a certain tag every frame, but that might have a bad performance, so better use a coroutine and only search every second or so. If you don't find any more elements, call a function and break out of the routine. If you want to continue to search, just restart the coroutine with StartCoroutine(Start());
Your answer
Follow this Question
Related Questions
Detect if Game Object has been clicked on in 3Dspace 1 Answer
Instantiated prefab warps immediately 1 Answer
How to spawn objects? 0 Answers
Non-host client doesn't seem to have authority when running Command 0 Answers
Spawning Meteors above a sphere 0 Answers