This trimester I have been looking into making a tool to use as extension for Unity. Due to my in UI I wanted to create a tool that assists in the creation of UI. Unity’s current UI system is already relatively easy to implement so I instead decided to take a look at the older Immediate Mode system used pre version 4.6.
Before I got to work I wanted to take a look at how Immediate mode GUI works and why anyone would need to use it over a retained mode system.
Unity’s immediate mode GUI system allows the user to create GUI elements without the use of GameObjects. Instead all GUI controls are handled within a single function call OnGUI().
The use of immediate mode GUI means that there is no need to cache any values anywhere as there is technically no “state” these elements exist in at all. The GUI will simply draw the current data it it is being given in the OnGUI() function. All rendering is performed in the application rather than through a graphics library, allowing greater potential for optimization.
(immediate mode gui)
(retained mode gui)
Creating Assets with Code
The idea behind my tool is to let a user input the number and type of GUI elements they want in their scene and to return a script on a gameobject in the scene with all values of position/size/any states available for editing in the inspector. This would help to create a balance between the two GUI systems. Immediate GUI elements you could move and position in the editor as you would with a gameobject based system.
However at first I had no idea how to actually go about creating the script to mange these elements through code. Enter StreamWriter.
The StreamWriter allows a user to output text into a separate text file at the location specified.
StreamWriter newText = new StreamWriter(“file location here.txt”);
However were you instead to give the output file the .cs extension instead, a new script is born.
StreamWriter newScript = new StreamWriter(“file location here.cs”);
To actually write to this new script, the new script we have created comes with the WriteLine function. This function does exactly what it says on the tin. Each time it is called it writes a string to the next line of the output file. For use in my tool, I would be able to write the functions needed to implement the users gui.
To correctly add this new file to the unity project it is also important that I run,
to update all asset folders to include the new script so that it can then be added to a new gameobject.