- Home /
Adding GameObject № 1 and GameObject № 10000 is different in CPU cost, why?
Dear Unity,
I noticed strange (at least for me) behaviour of unity. I would like ask if anyone can explain it.
Consider following code: Note that this code attached to empty GameObject as only component. Also there nothing else in this scene, it is completely empty.
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour
{
private int count = 0;
void Update ()
{
if(Input.GetMouseButton(0))
{
count++;
GameObject test = new GameObject("test");
}
if(Input.GetMouseButton(1))
{
Debug.Log(count);
}
}
}
This code adds new empty GameObject each frame while mouse button is held (incrementing int is for counting purposes).
The interesting thing is that, when adding ONE and first GameObject a fraction of CPU power is used.
But, when adding ONE GameObject to existent 10000 of GameObject much more CPU power is used for adding the same ONE GameObject.
NOTE: If you have problem in achiving such a result, it means you have a better CPU than me. Though, try adding more than ONE GameObject at once using this code:
...
GameObject test = new GameObject("test");
GameObject test1 = new GameObject("test");
GameObject test2 = new GameObject("test");
GameObject test3 = new GameObject("test");
...
If you will patiently hold mouse button for some time you will soon notice, ever growing CPU load, while amount of work is, on first sight, constant.
Now if you release button, CPU usage emmidietly fall to normal amount. Though if button pushed again, CPU will be loaded again back to same value. Eventually it will be loaded 100% instantly.
No matter how much GameObjects specific CPU can handle, but rule that every new GameObject consumes more CPU time to be created than previous is consistant.
Also it is remarkable that Unity running smoothly even with some 100 000`s (hundred thousands) empty GameObjects in scene, but if you were to add ONE more it will cause a huge freeze even on top rigs. Any idea why?
Please correct me if i put something wrong or miss cruel aspect.
Reason I could see, when starting you have free memory, after 10000 objects the memory may need to look for empty space. This seems even more probable since as you go, you tend to say the time increases. Just an assumption.
Have you tried this in a build? Sometimes the Unity Editor is a little special in it's performance with certain tasks.
Your answer
