- Home /
Object Pooling: deactivating vs. moving
Preface (skip if you want): I'm currently working on a 2d infinite runner that spawns "ground piecs" randomly from a list. Currently I Instantiate prefabs on the right side of the viewport and destroy them when they go off the screen to the left. I'm about to start optimizing this by implementing object pooling.
The Actual Question: Anyway my question is when I want to "delete" the object (move it back into the pool) is it better to use GameObject.SetActive(false) or to disable the components of the object and move it out of view?
This may sound out of context but why don't you just use Destroy(GameObject); then use Instantiate to spawn the items from a gameobject array? :)
That's what I'm doing currently but it's recently come to my attention that pooling is more performant.
When objects get created and deleted it causes the garbage collector to trigger frequently which can cause stutters every few seconds (which is what I'm experiencing).
Why wouldn't you just deactivate the GameObject? It automatically disables the components (even if you add or remove components dynamically), and it's a little less processing that Unity has to do every frame/timestep. I don't see any advantages to disabling the components.
Well that's the question isn't it. I assume that deactivating the GameObject would be better but in places where pooling has been discussed i.e. http://answers.unity3d.com/questions/321762/how-to-assign-variable-to-a-prefabs-child.html it seems like some choose to move the transform to an offscreen location. I'm curious about the differences.
If you only move the object off screen, the object will not be rendered but its scripts will still work.
If you disable it, and will not be rendered and its scripts will not work.
So your choice should be based on "do I need the scripts running after i'm 'removing' the object or not".
Answer by flamy · Nov 07, 2013 at 09:00 AM
It is your choice and depends on how you build the scene and stuff.
If you have a script with some code in update() function, then it is better to disable the whole game object. This is because even when out of focus UPDATE method runs on all objects
If it is simple gameobject without any scripts attached or some simple script without update (pick up objects would have only OnTriggerEnter()), just move it out of screen, that would do.
DONT go around disabling individual components, because you would have to have maintain lot of references.
My personal suggestion is to disable the object itslef, it is simple to do ;)
Your answer
Follow this Question
Related Questions
2D Vertical scrolling infinite background 1 Answer
What's the most efficient method of implementing an infinite parallax background? 0 Answers
Infinite Runner Tutorial - Destroyer Problem 2 Answers
cannot respawn pickup objects infinite runner / flyer 3 Answers
Programming Movement Momentum 0 Answers