Performance: Why everything in Unity is a GameObject
This concept affects how Unity manages scene objects and their rendering performance by structuring all entities as GameObjects with components.
Pre-create GameObjects with required components in the editor or during initialization. Reuse objects via object pooling instead of creating new ones every frame.
GameObject obj = new GameObject(); obj.AddComponent<MeshRenderer>(); obj.AddComponent<MeshFilter>(); // Adding many components dynamically every frame
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Dynamic GameObject creation every frame | High (many nodes) | Multiple reflows | High paint cost | [X] Bad |
| Pre-created GameObjects with pooling | Low (fixed nodes) | Single reflow | Low paint cost | [OK] Good |
GameObject as the base for everything in a scene?new GameObject().GameObject obj = new GameObject("Player");
Debug.Log(obj.name);new GameObject("Player") sets the name of the GameObject to "Player".Debug.Log(obj.name) prints the name property, which is "Player".GameObject obj; obj.AddComponent<Rigidbody>();
obj is declared but not assigned any GameObject instance.AddComponent on a null reference; obj must be initialized first.transform.parent to the parent's transform.transform.parent to the parent's transform. Code that assigns the parent's parent to children reverses the hierarchy. Code that uses parent.transform.SetParent(child.transform) also reverses the relationship. Assigning child1.transform = parent.transform; tries to assign transforms directly, which is invalid.Pass the test and this pattern moves unknown