- Home /
How can I hide a GameObject without active=false?
As far as I know, there are two ways to hide a GameObject.
The most popular way is GameObject.SetActive(false); But this method will disable all functions of it, and that is not my option.
Second way that I didn't successfully make it worked is GameObject.renderer.enable = false; Because I always got error message said : "MissingComponentException: There is no 'Renderer' attached to the "island01" game object, but a script is trying to access it." when I assign false to it. I don't understand why. There is a renderer object in GameObject indeed. Why I always got this error message?
I just want hide GameObject without set active property false. I believe that renderer.enable should be the answer, but I just can't assign value to it. Anybody knows the way?
FWIW note that in some games, you very simply move it off screen. depending on the situation this can be faster.
I don't think that can ever be faster. If you move it offscreen it still needs to be culled, whereas disabling the renderer means it's no longer part of the rendering process at all.
Answer by Eric5h5 · Mar 05, 2013 at 01:56 AM
GetComponent<Renderer>().enabled = false
is correct. If Unity tells you that there's no renderer attached to that object, then you can be 100% sure that there is no renderer attached to that object. Most likely the renderer is on a child.
I think my description lost some important conditions. I assign renderer.enable property on a GameObject that contain a NGUI's UISprite object only. So I tried parent object and child object both, and all them gave me the same error message. $$anonymous$$y thought is maybe both of them do not have renderer component indeed. Finally I set UISprite's enable property to false, and it works as expected. So, is it an answer? XD
Yes, in that case the error was because there was no renderer component at all. :)
Answer by illustir · Oct 21, 2015 at 02:30 PM
I found fiddling with the renderer to be not foolproof across 2D/3D.
My solution which looks to be fairly solid is to set the scale to [0] (and in the normal case to work with a scale that is [1]).
// Hide button
GameObject.Find ("ShareButton").transform.localScale = new Vector3(0, 0, 0);
// Show button
GameObject.Find ("ShareButton").transform.localScale = new Vector3(1, 1, 1);
GENIUS! Absolutely GENIUS! I love this solution! Just what I wanted!!! How did I not think of this myself....
One side effect, object is not visible but is likely to be kept in the rendering process. Not sure if Unity discard when scale is 0 (doubtful). $$anonymous$$oving out would result in object being out of camera frustum so not rendered.
Answer by RowanG1 · Mar 01, 2018 at 09:48 AM
Temporarily moving the object to behind the camera might be a solution.