Manager script(simple script attached to an empty GameObject on scene) on Start() instantiates 1000 default cubes with rigidbody component added and gravity check ticked.
public class SpawnScript: MonoBehaviour {
public bool MakeInstances = false;
public bool GC = false;
public GameObject instance;
public int numberOfInstances = 1;
void Start() {
if (MakeInstances)
for (int i = 0; i < numberOfInstances; i++)
{
Instantiate<GameObject>(instance);
//GameObject tempInstance = Instantiate<GameObject>(instance);
//GameObject.Destroy(tempInstance);
//tempInstance = null;
//Debug.Log("obj is " + tempInstance);
}
}
private void Update()
{
if (GC)
{
GC = false;
System.GC.Collect();
Resources.UnloadUnusedAssets();
}
}
Cube prefab have self destruction script like this
public class SelfDestruct : MonoBehaviour {
public float seconds;
IEnumerator DestructIn(float time)
{
yield return new WaitForSeconds(time);
Destroy(gameObject);
}
void Start () {
StartCoroutine(DestructIn(seconds));
}
}
Profiler "simple" shows memory usage around 0.7gb after instantiating is done. I expect it to get freed after destroy, but it does not. Tried to apply GC and UnloadUnusedAssets, did not help. Tried to destroy them all right after instantiating, still no luck.
Is it a bug or am I doing something wrong?
This is definitely not a real world example, just wanted to study memory management in Unity and got stuck here.
P.S.A few more strange points I have noticied with profiler:
- In Editor/"Detailed" mode it would not notice that I have 1000 cubes on a scene, while in Build/"Detailed" it did
- In "detailed"(both editor and build) data usage is around 200mb which is definitely not true(broken?), because Windows Task Manager shows me that build is using around 0.9gb. Bigger than what "simple" tells me, guess some overhead is present
EDIT:
Thanks to @Candid Moon for performing a test, he did confirm that software won't eat all the memory. Guess I should add screenshots with my observations
Here we have no instantiation, simple clean scene with a plane, eats around 100mb
Now let us go wild and make that instantiation on a startup
Alright, we did instantiate a lot of objects, they collided and flew away in outer space, in 5 seconds they were destroyed. We are back to clean scene with plane, just like the one with 100mb. Except for now it eats up 0.75gb. Left it hanging for half an hour to see if memory gets freed, nothing happened.
Is it a usual behavior? Is there any way to free all the used memory and go back to 100mb? Can/Should programmer do anything on his side to deal with such situations?