Called when the object dies but the program does not exit?

How to do it, only execute when the object is destroyed, not when switching scenes or exiting the game .

I want to remove the object from the list when the object is destroyed, but don’t do it when the scene ends because it is not necessary, because the list itself is also destroyed

Something like this:

void OnDestroy() {
  myList?.Remove(this);
}

This is also called when switching scenes or exiting the game. How to not call when switching scenes or exiting the game

But the object is destroyed when the scene is switched or the game exits.

What is the advantage of not making this call when the scene switches or the game exits? Why would you want to keep a destroyed object in your list?

Because the list itself will also be destroyed, remove is not necessary and wastes performance
Sometimes I want to use OnDestory to play the explosion effect when the unit dies, but I don’t need to do this when I exit the game

Like OnDestory=OnDie+OnExit
I only need OnDie

You could create an event and subscribe to it at runtime. When the Ondie is needed, call the event. In the event, remove the object from the list and play your effect. Eliminating onDestroy from the equation. Should do what you’re wanting.