Unity in the way of the destruction of the object of the game

Of destruction

There are two ways to destroy objects: the Destroy and DestroyImmediate two kinds , both that what difference does it? Listen Takahashi.

Two ways to achieve the purpose of the destruction of the object, with the following differences:

Destroy Destroy object in the scene, but there are still memory, or a period of time not to be used again, before dismantling and release memory, thus avoiding frequent read and write operations to memory, the system recovery will regularly clean the object is not referenced in memory , it is likely some places you still reference the object you do not know where, or where you ignored, can lead to the destruction of direct references cited local null reference error occurred.

DestroyImmediate is immediately destroy the object, and removed out from memory.

example

For example, you want to destroy 10 sub-object at a certain object, assuming that is to be destroyed under A a0 objects - a9,10 sub-objects

 1 ///<summary> 
 2 ///脚本挂在A物体上
 3 ///  <summary> 
 4 public class AGameOnject: MonoBehaviour  
 5     {  
 6 
 7         void Start ()  
 8         {  
 9             for (int i = 0; i < transform.childCount; i++) {  
10                 Destroy (transform.GetChild (i).gameObject);  
11             }  
12         }  
13 
14     }  

The code above can be achieved by the destruction of all child objects under A, but some people have doubts, why this place is GetChild (i), each behind a deleted object should not do to move forward? The index will be reduced by one.

So this is the mechanism Destroy, Destroy after executing, the program can not be immediately detected the object is destroyed to obtain the number is still 10.

But if you can not write a DestroyImmediate, as follows:

 1 public class AGameObject : MonoBehaviour
 2 {
 3 
 4     void Start ()
 5     {  
 6         int count = transform.childCount;
 7         for (int i = 0; i < count; i++) {  
 8             DestroyImmediate (transform.GetChild (0).gameObject);
 9         }  
10 
11     }
12 
13 }  

Because a DestroyImmediate execution will be destroyed immediately, and free up memory, the number will be minus one, the index of the object behind it will move forward.

to sum up

DestroyImmediate once destroyed will be destroyed immediately, and free up memory. Perform this operation requires more time, affect the main thread, asynchronous and Destroy is destroyed, usually in the next frame will be destroyed, this does not affect the main thread.

Please correct me.

 

Guess you like

Origin www.cnblogs.com/answer-yj/p/10931231.html