©2017 by Haikun (Quincy) Huang.

Search
  • Quincy Huang

[Unity] To avoid crash!!

Thanks for the smart GC.  Unity finally will crash at a certain point due to out of memory.  

It since the GC will only collect the garbage after the current scene is unloaded.  That means if you create lots of resources in the current scene, e.g., textures, audio clip or other class , frequently, your system may run out of memory and Unity will crash, even you call System.GC.Collect() explicitly. 

To avoid this critical problem, I would like to recommend you to use ScriptableObject, more detail please refer to https://docs.unity3d.com/Manual/class-ScriptableObject.html

You can treat it as a save-file at this time.

Let's start to improve your current work.

Assumes you have code:

for (int i=0; i<1000000; i++)

{

    // dirty job here, create a lot of local resources here.

}

You may finally crash at certain point. 

Now, follow me to simply improve the code.

Create a new script:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

[CreateAssetMenu( fileName="ForLoopCounter", menuName="ForLoopCounter")]

[System.Serializable]

public class ForLoopCounter : ScriptableObject {

    public int start=0;

}

Back to the project window, to create the scriptable object,  follow the steps: create->ForLoopCounter, and rename it whatever you want.

Then revise your code:

using UnityEngine.SceneManagement;

ForLoopCounter flc;

void Update(){

if (flc.start<1000000)

{

    // dirty job here, create a lot of local resources here.

    // move to next 

    flc.start++;

    // reload the current scene, after that, the GC will collect the garbage.

    SceneManager.LoadScene(SceneManager.GetActiveScene().name);

}


In the inspector, you will see the ForLoopCounter.start increase. Even you exit the playmode, ForLoopCounter.start would also not reset to 0.  That means, you can continue to start at the point you exited last time. ForLoopCounter here is like a save file that saves the value at runtime, and you can retrieve that value at the next run. But the important thing is your program finally would not crash due to the dirty job you created. I used this method to success do the object detection on 1300+ scene, download 1300+ HD images and 2500+ HD sound files at a run without crash in Unity.

You will notice that your memory stays in a good condition.


27 views