Hello, I have a list on witch i have every enemy on the map sorted by its distance to the tower (it’s a tower defense game) The problem is in the method i use to add those targets to the list, I can only use it once because i dont know how to clear the array inside it.
i’ve tried using ArrayName.Clear(); with no results, i can’t either get the lenght of it i guess because it’s a GameObject Array but not sure…
public void AddAllEnemies(){ GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy"); foreach(GameObject enemy in go){ AddTarget(enemy.transform); i++; } } public void AddTarget(Transform enemy){ targets.Add(enemy); } ` This is the most important part of the code witch i'll post at the end, when an enemy dies i am supposed to clear the list and then add every enemy on the map but when i do this, because i can't clear the "go" array i add the actual enemys and the previous ones, so i end up with the same list twice, but the main problem is that the enemy i killed is dead and therefor when i sort them by distance an error appears. Bottom line i need to clear the previous GameObject array everytime i call the AddAllEnemies method or find a way to update my "targets" list. Thanks to everyone who tries to help me, and i hope you can because i am a bit despered with this S:using UnityEngine; using System.Collections; using System.Collections.Generic; //using System; public class TowerStone : MonoBehaviour { public List targets; public GameObject projectile; public Transform target; private Transform myTransform; private float coolDown = 2; private float t; private int i = 0; private bool ready = true; private bool arrayOn = false; //private delegate Transform myDelegate(Transform t1, Transform t2); // Use this for initialization void Start () { myTransform = transform; float t = Time.time; AddAllEnemies(); TargetEnemy(); } // Update is called once per frame void Update () { TargetEnemy(); float c = Time.time - t; if (c > coolDown && ready){ t = Time.time; Fire(); } /*if(Input.GetKeyDown(KeyCode.Y)){ AddAllEnemies(); }*/ } void Fire(){ GameObject arrow = Instantiate (projectile, transform.position + new Vector3(0, 3, 0), Quaternion.identity) as GameObject; arrow.SendMessage("SetTarget", target); } public void AddAllEnemies(){ GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy"); foreach(GameObject enemy in go){ AddTarget(enemy.transform); i++; } } private void SortTargetsByDistance(){ targets.Sort(delegate(Transform t1, Transform t2){ return Vector3.Distance(t1.position, transform.position).CompareTo(Vector3.Distance(t2.position, transform.position)); }); } public void AddTarget(Transform enemy){ targets.Add(enemy); } private void TargetEnemy(){ SortTargetsByDistance(); target = targets[0]; ready = true; } private void TargetDestroyed(){ targets.RemoveAt(0); ready = false; SortTargetsByDistance(); print (target); } void AddMe(){ } }`