How do I disable a Renderer on a UI object in 4.6

Hey everyone,

I have been told by my programmer friends that having completely alpha-d out objects in a scene is bad for optimization since the engine still has to render them. Currently, I typically just sett the alpha to 0, and am trying to fix that habit, but I can’t figure out how to disable rendering on a UI object.

I know this must be a super simple answer but I’m trying to disable a UI object from rendering. The object in question is an Image I have stored in code as “starsVisual” but when I try this code:

starsVisual.renderer.enabled=false;

I get this error:

MissingComponentException: There is no ‘Renderer’ attached to the “Stars” game object, but a script is trying to access it.

I am assuming that I need to use something else for 2D UI as opposed to the above code which is used for 3d objects in all of the examples I have found. Thanks.

Hi, I think there is no way to disable a single UI object without performance impact.
You can see the performance impact when enabling or disabling a whole UI window to hide it.
Also UI elements out of the screen continues to consume rendering time, so alpha and “out of the screen” are not solutions for UI elements.

What gave me a really good performance was to add a Canvas element to the main parent of the UI group that you want to hide (the Panel containing your window).
So setting the enable property to false will automatically stop rendering the whole group in just a single frame, also will appear again setting it to true.

Note that all of your scripts will continue executing normally.

What worked for me is instead of looking for CanvasRenderer, I looked for UnityEngine.EventSystems.UIBehaviour, the base class of the UI Components we use such as Image. And then from getting these, you can access the .enabled property.

Example:
UnityEngine.EventSystems.UIBehaviour[] allUI = gameObject.GetComponentsInChildren(); foreach(UnityEngine.EventSystems.UIBehaviour ui in allUI) { ui.enabled = false; //turn them off. }

Try:
Using UnityEngine.UI;

A UI object in Unity 4.6 has a CanvasRenderer component and not Renderer. So you need to disable that. You can do it as:

starsVisual.GetComponent<CanvasRenderer>().enabled=false;