Unity は、ガベージコレクター を使用して、アプリケーションや Unity が使用しなくなったオブジェクトからメモリを回収します。スクリプトがマネージヒープ上で割り当てを行う際に十分なヒープの空きメモリがない場合、Unity はガベージコレクターを起動します。ガベージコレクターを実行すると、ヒープ にあるすべてのオブジェクトを調べ、アプリケーションが参照しなくなったオブジェクトに削除のマークを付けます。Unity は参照されていないオブジェクトを削除し、メモリを解放します。
ガベージコレクターは、必要なブロックサイズを割り当てるのに十分な大きさの空き領域がなくなるまで、継続するリクエストを同じ方法で処理します。この状況では、割り当てられたすべてのメモリがまだ使用されている可能性はあまりありません。Unity のスクリプトバックエンドは、その場所を特定できる参照変数が存在する間だけヒープの参照アイテムにアクセスできます。メモリブロックへのすべての参照がなくなると (参照変数が再割り当てされた場合や、参照変数がスコープ外になったローカル変数で場合)、ガベージコレクターは占有していたメモリを再割り当てすることができます。
どのヒープブロックが使用されていないかを判断するために、ガベージコレクターはすべてのアクティブな参照変数を検索し、それらが参照しているメモリブロックを “live” (ライブ) とマークします。検索が終わると、ガベージコレクターは “ライブ” ブロックの間のスペースが空であると判断し、その後の割り当てに使用するためにマークを付けます。未使用のメモリを探して解放するプロセスは、ガベージコレクション (GC) と呼ばれます。
ノート: WebGL では、ガベージコレクターの動作が異なります。詳しくは、ガベージコレクションの注意点 を参照してください。
Unity では、ガベージコレクターには以下のモードがあります。
Unity には、メモリの割り当てを追跡するための以下のツールがあります。
CPU Usage モジュールでは、Hierarchy ウィンドウ に GC Alloc 列があります。この列は、Unity が特定のフレームでマネージヒープに割り当てたバイト数を表示します。また、ガベージコレクターが管理したメモリの量も表示されます。またこれには、Unity が後続のフレームで割り当てて再利用した可能性のあるメモリも含まれます。つまり、すべてのフレームの GC Alloc の合計は、その間のマネージメモリの増加量を合計するものではありません。
最も正確な情報を得るためには、常に、ターゲットとするプラットフォームやデバイスの開発ビルドでアプリケーションをプロファイルする必要があります。Unity エディターはビルドとは異なる方法で機能し、これはプロファイリングデータに影響します。例えば、 GetComponent
メソッドは、エディターで実行される場合に常にメモリを割り当てますが、ビルドされたプロジェクトではそうではありません。
また、Profiler の Call Stacks モード を使用して、どのメソッドで割り当てが行われているかを判断することができます。GC.Alloc サンプルのフルコールスタックトレースを有効にして、ガベージコレクターがいつどこで実行されたかを判断することができます。
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.