UNITY Destroy()和DestroyImadiate()都不会立即释放对象内存
生活随笔
收集整理的這篇文章主要介紹了
UNITY Destroy()和DestroyImadiate()都不会立即释放对象内存
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
UNITY Destroy()和DestroyImadiate()都不會立即釋放對象內(nèi)存
如題,destroyimadiate是立即將物體從場景hierachy中移除,并標(biāo)記為 "null",注意 是帶引號的null。這是UNITY內(nèi)部的一個處理技巧。關(guān)于這個技巧有很爭議。
destroy要等到幀末才會將物體從場景層級中移除并標(biāo)記為"null"。
不管如何,二者都只是UNITY引擎層面的標(biāo)記與處理,但在.NET底層,對象的內(nèi)存都沒有釋放,只有手動GC.COLLECT或等待NET去GC時才會釋放掉對象內(nèi)存。
測試代碼如下:點ADD按鈕不斷創(chuàng)建對象,點DEL按鈕清除所有對象,通過觀察進(jìn)程內(nèi)存數(shù)值來察看對象內(nèi)存是否釋放。
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 }?
posted on 2017-09-22 15:09 時空觀察者9號 閱讀(...) 評論(...) 編輯 收藏
總結(jié)
以上是生活随笔為你收集整理的UNITY Destroy()和DestroyImadiate()都不会立即释放对象内存的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于LOH(Large Object H
- 下一篇: Android内存分析和调优(上)