Destroy not destroying in time

Hey all, got another stupid question for you smart folks

I have "Cell" objects that destroy themselves when they run out of health, that part works fine.

I'm keeping a list of these objects in a global static array/"gameData" object in the scene. The function within the cell that destroys itself calls the gameData object's updateCells() function that updates the public list of all the existing cells in the scene. The problem is the cell isnt actually destroyed by the time updateCells is called, so it has a slot in the allCells array after it's been destroyed. I only call updateCells when a cell is instantiated or destroyed to save cycles, but currently the allCells array is inaccurate until another cell is born.

What's the best way to tell this gameData object that the cell is in the queue to be destroyed, so it isnt counted in the array of living cells?

For further confusion, the code works fine if the cell dies on it's own, but doesn't work properly when I shoot/kill the cell, and both occurrences call on the same exact code. The "natural" death is being calculated within update() and I guess being killed is somehow inbetween updates.

thanks all! -Chris

Depending on what you're doing, how you're doing it and how you're calling this UpdateCells method of yours, the solution may vary. The easiest solutions would generally be to either:

(A) use MonoBehaviour.Invoke(…) which calls a function of your choice, and tell it to invoke your update method in, say, 0.2 sec or so,

(B) keep some kind of ‘alive’ flag on the cell and set it to false as you’re destroying it, so that if the update occurs before it’s fully destroyed it will be ignored/skipped/removed manually, or

(C) if you’re using C# you can make an Event system using Delegates and Events, where your list, usually a Singleton-type manager object ‘listens’ for events and can register itself with every one of your objects (cells in this case), and as they die they will call their death method which will evoke the listener’s OnDeath (or similar) method, which will tell it to remove said object from queue.

For more on C# events, just google C# delegates, and C# events, along with the word MSDN in the search, and you'll get right to the info and the example code. OR, if you say your system seems to work some of the time, you can try just debugging it a little to figure out why it may be failing other times, it might be something simple you overlooked.