- Home /
Calling setActive(false) on a disabled object?
I have read that calling setActive is performance heavy, and should be avoided when possible. I can confirm this, as the game hiccups when calling setActive on large numbers of objects. If I call setActive(true) on an already enabled object, or setActive(false) on an already disabled object, will this still cause lag despite the object state not changing?
Answer by TimHeijden · Aug 04, 2015 at 01:18 AM
Like Dave said, try it out :P
It doesn't sound likely though, the reason SetActive() would be performance heavy is because it triggers all kinds of things. An example is that all components (for scripts, OnEnable/OnDisable) on the gameObject AND all child gameObjects have to be activated. Colliders / rigidbodies probably have to be (un-)registered to the physics engine and so on.
When an object is already enabled or disabled, one would assume Unity would be competent enough to detect this and not cause performance issues.
Answer by TonicMind · Dec 17, 2015 at 04:36 PM
I have to correct TimHeijden said. As with anything SetActive() is not inherently (by default) inefficient. It depends on the situation! If you are constantly reusing the same prefab then it makes more sense to use an object pool. Doing that saves a lot of processing power. I recently implemented an object pool in my game and it gets a full 60 fps now. Think about it, if you need something many times per second why would you just create a new one every time it was needed? That was actually more work than when I implemented the object pool!
Why go through all that work when you can call one method to disable it?
Check this out: https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling
They use an objectpool which does use SetActive() many times a second for their repetitive task. It doesn't cause efficiency problems at all!
I just wanted to update this question I found while searching for information on something, because I think the selected answer is misleading.
Answer by Zahidylin_Marat · Aug 08, 2018 at 08:21 AM
Was thinking many times:
So if object is already not active gameObject.activeSelf == false than
gameObject.SetActive(false)
have the same performance as
if( gameObject.activeSelf == false) gameObject.SetActive(false)
If call it in Update all the time:
void Update()
{
gameObject.SetActive(false);
}
Right?
Your answer
Follow this Question
Related Questions
Alternatives to GameObject.SetActive(...) 2 Answers
Bool activate/de-activate on timer C# 1 Answer
I Can't disable gameObject using .SetActive (or anything else) 2 Answers
enabling / disabling child objects 1 Answer
Scipt Not Functioning Properly 1 Answer