Hello, I am trying to keep a counter of gameObjects, then run a loop and destroy those gameObjects when cubicideCount == 1. My code works, but only sometimes. I noticed a couple things.. 1. The enemyCounter.Count hits a limit of 30 then stays there. 2. The enemyCounter.Count will count properly for a while, then get all sporadic switching between 1 and 0. Please note that cubicideCount is incremented somewhere else in a OnCollisionEnter(). Code (CSharp): using UnityEngine; using System.Collections; using System.Collections.Generic; public class CreateCubes : MonoBehaviour { void Start () { //==Loop the Create() which creates an enemy every second.==// InvokeRepeating ("Create", 1, 1); } void Update(){ //==Check if enemyCounter is equal to 1, and run a for loop to destroy every gameObject in the list.==// //==Then==// if(GameObject.Find("Player(Clone)").GetComponent<CollideAndExpand>().cubicideCount == 1){ for(int i = 0; i < enemyCounter.Count; i++) Destroy (enemyCounter[i].gameObject); enemyCounter.Clear(); GameObject.Find("Player(Clone)").GetComponent<CollideAndExpand>().cubicideCount = 0; } } //======Create the enemy and assign it an element in a list======/ void Create () { enemyCounter.Add((GameObject) Instantiate (enemyCubes, randomBoxLocation, transform.rotation)); } }
I'm guessing this is partial code, because enemyCounter, enemyCubes and randomBoxLocation arn't declared anywhere. First big thing I see is that you should be caching the CollideAndExpand component, instead of looking for it twice every frame. That's an expensive operation. Like so: Code (CSharp): CollideAndExpand collideAndExpand; void Start () { //This assumes that your player object has a player tag, has a CollideAndExpand component, and that the //player object is created before this script executes. If it doesn't, you could always check collideAndExpand //for null in the update loop and find it there. That way it only looks for it once. collideAndExpand = GameObject.FindGameObjectWithTag ("Player").GetComponent<CollideAndExpand> (); } Anyway, superceding that, I'm betting the problem is originating from another part of your code. Although I would have written this differently, this will behave as expected.