Why does script continue executing when turned off or destroyed?

Started working on a script i plan to publish, in doing so i am making LogWarnings and such for end users. I came across this, not so much problem, but undesired effect and am curious as to how the unity pipeline runs/interprets the code.

I have a check to make sure that an array(builtin) is populated, if there is nothing there i destroy the script(turning it off isnt fast enough, surprisingly). The ‘issue’ arises right after i destroy the script, since i make a function call right after the check the script continues to run for 1 more line(thus throwing a null since the array is not populated, even tho the script was ‘destroyed’ right before(i want the user to only see my Log Warning(not the un-descriptive null ref we all hate getting :stuck_out_tongue: ). I have managed to get around it by using Destroy(this); followed by a yield;

Im curious though:

Why does it continue running?

How, when i use this.enabled=false; followed by yield;, is it still able to run the function and first line inside?

Heres some sample code for a quick read example (length is declared as waypoints.Length)

Runs first line of function Foo (BAD)

else if(length==0)
{
    Debug.LogWarning("Assign waypoints to the waypoints array");
    this.enabled=false; //or //Destroy(this);
}
Foo();

Runs first line of function Foo (BAD)

else if(length==0)
{
    Debug.LogWarning("Assign waypoints to the waypoints array");
    this.enabled=false;
    yield;
}
Foo();

Works (does not run function Foo) (GOOD)

else if(length==0)
{
    Debug.LogWarning("Assign waypoints to the waypoints array");
    Destroy(this);
    yield;
}
Foo();

Again mainly just curious how the script executes(this is a very small amount of time here, ~ 1 frame). If anyone wishes to explain id be grateful, even tho it isnt of huge concern it may help others(and myself for that matter) understand the engine a bit better.

Script execution doesn’t stop immediately when you disable or destroy an object. That’s perfectly normal. If you want to exit your current function, use return.

As Unity scripting manual states “Enabled Behaviours are Updated, disabled Behaviours are not.” That doesn’t stop you from calling specific methods from them though.

You can try DestroyImmediate as Destroy method is a delayed method and maybe that’s why it appears to be slow.