So I have enemies that spawn, and when they do, a door spawns also. When the enemies all die, i want the door to be deleted. I am trying to have the object be deleted by checking an array is empty and also a variable is true. But for some reason the array is not being checked all the time. Is there someway I need to check for the array length in the update function? Or have I completely this this idea up wrong
In your first approach, be advised that in C# arrays are immutable in length: once you make them, you canât add/remove entries. You can set the entries to null however, but simply destroying something does not remove it from the array, hence it doesnât change the array .Length
The second approach might work but is VERY non-performant: GameObject.FindgameObjectsWithTag() is a âheavyâ function and should probably only be called sparingly, like at level startup or level ending. Youâre calling it every frame.
If youâre finding the DoorDeletion is not working, attach the debugger and put a breakpoint on line 13 and then find out which of the two conditions are not true. Or just put those two values out to Debug.Log() so you can see what they are when the game is running.
I think you should try a new approach. When you spawn the enemy, increment a counter. Now, when this enemy dies, tell the spawner script that youâve died, and the spawner script will decrement the variable.
Now you only have to check for the enemy count when one dies, compared to every update loop. It makes a lot more sense. If thereâs some extra logic about âisCreatedâ, try to add that in (Iâm not sure what that is, or if you even need it*).
I have set up the counter and it is all working fine now, but was hoping you could answer something else in regards to it.
From another script I am accessing the counter with GameObject.FindWithTag("EnemyTrigger").GetComponent<EnemySpawner>().EnemyCounter -=1;
But should I not be able to create an int and assign it to above in the start function, and then just use the int i created to change the counter. ie -
public int EnemyCounterScript;
void Start()
{
EnemyCounterScript = GameObject.FindWithTag("EnemyTrigger").GetComponent<EnemySpawner>().EnemyCounter;
}
if (Health <= 0)
{
EnemyCounterScript -=1
}
No, that wonât work because an integer is copied not referenced. All value types work like that: float, int, Vector3, etcâŚ
Iâm glad itâs working in general for you now.
You could âimproveâ this a little bit, too, if you stored a reference to the EnemySpawner on the enemies. When you spawn them, assign âthisâ from the spawner to the new enemy (its script).
Then, when they die, you can use that reference to call the method. Itâs just a little more direct that way, and avoids a âFindWithTagâ call. The result should be the same, though