- Home /
Destroy script still works on
Hello, when I try to destroy the gameObject, it's still working on and print out "5", how can I reach that that the code stops?
void Awake() {
Destroy(gameObject);
int i = 5;
print(i);
}
(It's only a simple example because I think any other longer script will just confuse you ;))
Answer by ShadyProductions · Jul 09, 2017 at 10:08 PM
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.
Yes, for a more realistic case you might find it suitable to store a bool something like isSetToDestroy. And if isSetToDestroy is true (you would set it true anytime you call Destroy()) then you don't do anything else. Unity may have something built-in but it's likely to be just like what I'm saying in practice.
Answer by Cornelis-de-Jager · Jul 09, 2017 at 10:19 PM
Well the most simple is way is via the following:
if (destroyCondition) {
Destroy (GameObject);
return; // <---------- Stops the rest of the script from running
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Destroy an enemy without destroying the player 1 Answer
Help with Spawning & Destroying Background Objects in 2D 2 Answers
Instantiating Objects 1 Answer