i have this little problem. i have array and i already set the size in declaration. but when i try put the variable to that array , the size of the array is always changing.
this is the example code :
public GameObject[] enemy = new GameObeject[4]; // i also set the size 4 in the inspector
void update()
{
enemy = GameObject.FindGameObjectWithTag("Enemy");
}
as you can see the example code. i try to put the gameobject enemy into the array. but i cant do it in the inspector because the enemy is not created just yet. with the code above the size of enemy is always change.
what i want is when the one of the enemy index is null , it is not change the size? anything would help. thanks
You need to make it so every update, the array is compared with a new array (with new entries), and those entries are ADDED if they don’t have an equal one in the original one
void Update() {
// Get a new array with an updated list of gameobjects
GameObject[] UpdatedArray = GameObject.FindGameObjectWithTag("Enemy");
// Go through the updated array and if it cannot find an equal object in the other array, then ADD itself to the array
foreach (GameObject itemUpdated in UpdatedArray) {
bool Original = true;
foreach (GameObject itemOriginal in enemy) {
if (itemUpdated == itemOriginal) {
Original = false;
}
}
if (Original) {
// My "complex" script for ADDING to an array
GameObject[] AddOriginalArray = enemy;
enemy = new GameObject[AddOriginalArray.length + 1];
int Selection = 0;
foreach (GameObject item in AddOriginalArray) {
enemy[Selection] = item;
Selection += 1;
}
enemy[Selection] = itemUpdated;
}
}
}
enemies = FindObjectsOfType();
will return all your enemies, and recreate the array to the new size every time.
Arrays are basically terrible in comparison to Lists because of the dynamic aspect, an Array cannot be added to, only its entries can be changed. Even a list is just an Array with more features. RAM is allocated to vars on the creation of them, as such EVERY time an array needs the size altered, it copies the contents over and creates a new array in a new RAM address.
As such I highly suggest switching to lists, and having an overall enemy list which can be empty on the start and every enemy could have this on his script
void OnEnable()
{
if (npcHandler.enemies == null)
{
npcHandler.enemies = new List<enemy>();
}
npcHandler.enemies.Add(this)
}