Adding UI Elements
And updating them after adding them
We will diverge from our Galaxy Shooter app and work on our side app for this one. It seems like a cleaner setup. And, sometimes a spawning mess is a lot more fun to look at.
Adding a Text component automatically adds it to a Canvas and also adds the required EventSystem.
One of the coolest features of the text box is being able to snap it to a location and adjust based on that location.
We will use the SpawnMonster demo scene for this setup. We will increment a count of each shape that is spawned.
I set up the Text elements so we had one Label element which stays the same and one text element which will be updated with the count.
Adding the UIManager
Create a script to handle our UIManagement. We could add the script component to a GameObject but a cleaner method would be to add it to our Canvas element since that houses all of our text elements anyways.
The UIManager’s job is to update UI components. In order to do this we will need to add Text object references to the desired components.
This will work but, with a trained eye, you can see that this is pretty bad. Look at all of the duplicated code.
Let’s refactor this to an array of Texts.
Calling an update
Now that we have our text fields ready to receive updates, how do we call the update??
First lets set up an array of ints for our counts.
We will also need a reference to the UIManager.
We then have to find our UIManager as well as initialize our int array. The call to GetComponent is expensive so we want to do it as few times as possible. Since we only have a single UIManager, find it first then use the reference.
In our update method we randomly select a Vector3 coordinate and a shape id. We then Instantiate the new GameObject from the Prefab array, increment the count of the id, and then use the UpdateCount method from the UIManager to update our UI.