"How to make Object X spawn when there're no more Objects tagged ""XYZ"" in scene?" (166894)

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?

1 Answer

1

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());