UNITY Destroy()和DestroyImadiate()都不會立即釋放對象內存


如題,destroyimadiate是立即將物體從場景hierachy中移除,並標記為 "null",注意 是帶引號的null。這是UNITY內部的一個處理技巧。關於這個技巧有很爭議。

destroy要等到幀末才會將物體從場景層級中移除並標記為"null"。

不管如何,二者都只是UNITY引擎層面的標記與處理,但在.NET底層,對象的內存都沒有釋放,只有手動GC.COLLECT或等待NET去GC時才會釋放掉對象內存。

測試代碼如下:點ADD按鈕不斷創建對象,點DEL按鈕清除所有對象,通過觀察進程內存數值來察看對象內存是否釋放。

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using System.Diagnostics;
 4 using UnityEngine;
 5 using UnityEngine.UI;
 6 
 7 public class MyGo : MonoBehaviour
 8 {
 9     byte[] data = new byte[83000];
10 }
11 public class testad : MonoBehaviour {
12 
13     Transform objs;
14     Text txt;
15 
16     Process proc;
17     // Use this for initialization
18     void Start () {
19         var btnadd = transform.Find("btnAdd").GetComponent<Button>();
20         btnadd.onClick.AddListener(OnClckAdd);
21         var btndel = transform.Find("btnDel").GetComponent<Button>();
22         btndel.onClick.AddListener(OnClckDel);
23 
24         objs = transform.Find("objs");
25 
26         txt = transform.Find("Text").GetComponent<Text>();
27         proc = Process.GetCurrentProcess();
28     }
29 
30     void OnClckAdd()
31     {
32         for (int i = 0; i < 20; ++i)
33         {
34             var go = new GameObject();
35             go.AddComponent<MyGo>();
36             go.transform.SetParent(objs);
37         }
38     }
39 
40     void OnClckDel()
41     {
42         for (int i = objs.childCount - 1; i >= 0; i--)
43         {
44             GameObject.DestroyImmediate(objs.GetChild(i).gameObject);
45         }
46 
47         System.GC.Collect();
48     }
49     // Update is called once per frame
50 
51     float timer = 0;
52     void Update () {
53         if (timer > 0.5f)
54         {
55             timer = 0;
56             txt.text = ((int)(proc.WorkingSet64 / 1024)).ToString();
57         }
58         timer += Time.deltaTime;
59     }
60 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM