Quantcast
Channel: Questions in topic: "count"
Viewing all articles
Browse latest Browse all 187

How to count child gameobjects with tag

$
0
0
Hi, I am trying to create a function that spawns enemies. However, I want the script to count the number of children with the tag "enemy" and only spawn if that number of children is less than the spawn count variable. I have written code to do this, but the update function fills the list immediately, because its counting and adding per frame. How can I get it to only count the game objects each frame and update the total number, rather than adding to the list? Here is the code I am using: using UnityEngine; using System.Collections; using System.Collections.Generic; public class ScriptObjectMonsterSpawner : MonoBehaviour { public GameObject monster; public GameObject[] spawnPoints; public GameObject particle; private GameObject currentPoint; public List Children; private int index; public int spawnAmount = 5; public float spawnRate = 5.0f; private bool spawning; // Use this for initialization void Start() { particle.SetActive(false); } // Update is called once per frame void Update() { if (transform.childCount < spawnAmount && spawning == false) { StartCoroutine(SpawnMonster()); SpawnMonster(); } foreach (Transform child in transform) { if (child.tag == "Enemy") { Children.Add(child.gameObject); } } } public IEnumerator SpawnMonster() { spawning = true; particle.SetActive(true); spawnPoints = GameObject.FindGameObjectsWithTag("SpawnPoint"); index = Random.Range(0, spawnPoints.Length); currentPoint = spawnPoints[index]; var newmonster = Instantiate(monster, currentPoint.transform.position, currentPoint.transform.rotation) as GameObject; newmonster.transform.parent = gameObject.transform; yield return new WaitForSeconds(spawnRate); particle.SetActive(false); spawning = false; } } Thanks in advance for any help :)

Viewing all articles
Browse latest Browse all 187

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>