So from my understanding there are two ways to do the GUI:
You can use the OnGUI() method and make a bunch of calls to GUI.Label() and GUI.DrawTexture() and so on to create everything.
Or you can have an object with a Canvas, and have a bunch of children with RectTransform (s), each being a separate part of the GUI with the text ones using the Text component or Image components.
My question is, is there any reason to prefer one method to the other?
- My friend has told me that OnGUI() is terrible for efficiency and should be avoided at all cost. He didn’t explain why this is. Is this true? Why is it true? Are there times when onGUI() would be more efficient?
- As far as I understand, there is nothing one can do that the other cannot. True? For example let’s say we want a Halo style motion sensor in a corner, I would think maybe a Canvas would be better for this with each dot being another RectTransform? Are there things that one can do that the other cannot do, at least well?
- Canvas seems to be easier to use if you want to do stuff like have text expand and shrink during events, but maybe not.
OnGUI() is the way of the past. Canvas has only been around since 4.6, and for almost all use-cases will be what people recommend using. Even the documentation for OnGUI (I guess now called “Immediate Mode GUI” or IMGUI) states:
“IMGUI is a code-driven GUI system, and is mainly intended as a tool for programmers.”
“The IMGUI system is not generally intended to be used for normal in-game user interfaces that players might use and interact with. For that you should use Unity’s main GameObject-based UI system, which offers a GameObject-based approach for editing and positioning UI elements, and has far better tools to work with the visual design and layout of the UI.”
So from this I’d infer that IMGUI is supposed to only be for debugging (but really it’s stuck in there for backwards-compatibility), while the new UUI stuff is supposed to be used for true end-User Interfaces.
Simply put, OnGUI() is the “old” way of doing GUI, while canvas is the “new” replacement. I can’t remember exactly when it was introduced, but OnGUI been in since at least Unity 3.x, probably earlier. Canvas was only introduced in Unity 4.5.
Canvas is to be preferred in all cases of new development - it is more efficient and more feature-rich. AFAIK, one of the only reasons why OnGUI has not been deprecated is because it’s the same codebase that is used to draw GUI functions in the editor. However, in that case, it’s fine to use.
Your friend is correct - OnGUI has appalling performance and many other quirks (OnGUI is called multiple times per frame, since it is called to both lay out the GUI elements on the screen and then again to render them).