March 6, 2019
Tower Defense Tutorial
Episode 26 – Fading
Youtube – How to make a Tower Defense Game (E26 LEVEL SELECT) – Unity Tutorial
By: Brackeys
Ep. 26
This tutorial gets into creating a level select menu for the player.
This would require its own scene, so we duplicated the Main Menu scene as a place to start since it’s already fairly empty. We started by setting up the hierarchy of UI assets for the level content selection area. It was noted that this is a general way to setup a scrolling menu for selecting objects in Unity.
The hierarchy is as follows:
- UICanvas
- Title
- Levels
- ScrollRect
- Content
- ScrollRect
We then added a button to our Content UI object, and gave that object a Grid Layout component. This allows Unity to place everything in an even grid layout for you. We also added a Content Size Fitter. This helps allow the object it is attached to scale to fit the content placed in it. We also made sure to move the pivot anchor point of this UI object to the top of the object to make sure it scales downward from that point instead of out from the center.
We added a bunch of buttons to help see that all of the scaling and clipping was working properly with the UI elements. To help keep them from flowing out of the menu (which also works with the idea of creating a scrolling menu), we added a Rect Mask 2D component to the ScrollRect object which blocked out child objects that were not within this rectangle space.
Speaking of scrolling, we added the Scroll Rect component to the ScrollRect object next. This just required dragging in the ScrollRect object as the viewport and the Content object as the content to start this working. This did have a slight issue for me where it seemed that I could only scroll if I clicked/held on a button in the content area. If I clicked/held on an empty space within the content area, I could not scroll the menu, so that would have to be fixed.
We created a simple LevelSelector script and placed it in an empty gameobject. This script provides the method for the onclick event for each of the buttons to reference to take the player to the corresponding level. To help test this, we just duplicated our initial level and changed the number of lives to create a level 2.
Finally, we added a scrollbar component to the Levels object to go along with the scrolling of our scroll rect. It just gives another, clearer option for scrolling, especially for someone using a computer.
SUMMARY
- Check pivot/anchor point locations for scaling UI elements, especially those using a component like Content Size Fitter.
- Implementing scrolling into UI elements in Unity is straightforward with ScrollRect and Scrollbar components.