How to make menu in unity

How to make menu in unity

Как создать меню для игры на Unity

Без меню игроку не изменить настройки, не сохраниться или не загрузить прошлый прогресс. Объясняем, как сделать меню в Unity.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Если вы уже немного понимаете, как работать в Unity, и попробовали что-то создать, пора научиться верстать игровые меню. Если нет, прочтите для начала статью о создании игры.

Здесь будут описаны общие моменты, с полной версией проекта можно ознакомиться, скачав его из репозитория на GitHub.

Для создания интерфейсов, в том числе и меню, в Unity используются
UI-объекты. К ним относятся:

Чтобы работать с ними, нужно создать объект Canvas и дать ему понятное название. Например MenuCanvas. Добавьте в него объект Panel и задайте какое-нибудь фоновое изображение или цвет.

После этого можно начинать верстать меню. Создайте внутри MenuCanvas объект типа Empty и назовите его MainMenu. Внутрь него можно добавить элементы типа Text и Button.

Менять надпись на кнопке можно с помощью вложенного объекта Text. Добавьте их столько, сколько вам необходимо. Затем разместите их на холсте так, чтобы получить что-то вроде этого:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Ваше главное меню готово. Нужно ещё добавить отдельные подменю для настроек, сохранения и загрузки.

Как добавить несколько меню в Unity

Чтобы создать несколько экранов меню, добавьте ещё несколько объектов типа Empty и поместите новые элементы в них. Например, в этом проекте будут созданы SaveMenu, LoadMenu и SettingsMenu.

При добавлении объекта он становится активным, поэтому все кнопки и слайды будут просто налезать друг на друга. Чтобы отключить какое-нибудь меню, нажмите на его объект и в Inspector возле его названия уберите галочку.

Этому действию соответствует метод SetActive(), который можно использовать, чтобы переключать меню при нажатии кнопки. Для этого выберите кнопку и в окне Inspector найдите поле On Click ().

В нём описаны действия, которые будут выполняться при клике на кнопку.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

На скриншоте показано отключение основного меню и включение меню с сохранениями при нажатии кнопки SaveButton. Сделано всё это без использования кода.

Как создать меню настроек в Unity

Отдельно рассмотрим создание настроек игры. Чтобы реализовать их, нужно сначала сверстать меню с помощью объектов Toggle, Dropbox и Slider:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Дальше создайте скрипт Menu.cs и прикрепите его к MenuCanvas: он будет отвечать за работу со всеми настройками.

В него нужно добавить следующие библиотеки:

Unity Create Main Menu With UI Canvas

User Interface (UI) is a combination of graphics, text, and buttons that plays a key role in providing an enjoyable gaming experience.

Main Menu is one of the most prominent parts of the UI since it’s usually the first thing that players see when loading the game.

In this tutorial, I will be showing how to create a Main Menu in Unity using UI Canvas.

Step 1: Design the Main Menu

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

SC_BackgroundScaler.cs

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Now we will create Menu buttons:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

However, you will notice that the text disappeared, that’s because the Rect Transform dimensions are too small. Change them to something bigger (ex. Width: 400 Height: 100), also move it up slightly by changing Pos Y to 50:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Step 2: Program Menu Buttons

Now we need to make the Buttons functional by creating a script.

SC_MainMenu.cs

The last step is to bind SC_MainMenu functions to each Button.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

The Main Menu is now ready.

NOTE: PlayNowButton() function in SC_MainMenu.cs will attempt to load a Scene called «GameLevel». So make sure you have a scene with the name «GameLevel», which is also added to Build settings (alternatively you can change the name in that line to correspond to the name of the Scene you want to load).

Interested in learning more about UI creation? Check our tutorial on How to Make Mobile Touch Controls in Unity.

Learn Unity Editor Scripting: Menus (Part 4)

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

In this post we will learn how to create menu items in Unity Editor to perform different tasks. You can add menu items to the main menu, or the context menus in the Inspector window.

This article is part of a series in which I explain all the techniques for extending the Unity Editor. See the overview post here.

Prerequisite: You need to know C# programming and be familiar with Unity Editor to benefit most from this post.

There is an accompanying Unity project. I highly recommend downloading it and trying the topics as you read them here. Seeing the examples in action makes them stick to your brain.

hk1ll3r/LearnUnityEditorScripting

This is the acompanying repository for my series on Unity Editor Scripting. You can find the articles down below. In…

For instructions on how to get started with the project, see the overview post.

Without further ado, let’s jump in!

Unity’s Main Menu

We can add menu items to the menus in Unity using the MenuItem attribute. The attribute takes 3 parameters:

A menu item will invoke a static method.

Let’s create a menu item! In the previous post, we created a validation method for the scene in our GameManager class. Let’s write a more general static validation method. The method ValidateScene will first search for the GameManager component in scene and show and error message if one is not found. If it is found it calls the validation method on our GameManager component.

Create a file named MyMenus.cs under the Editor folder in your project and paste this into it (need to add using statements to the top.)

After you save switch back to Unity Editor, our menu will get added to the top.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Pressing it will show a dialog with the result of the validation.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Creating new top level menu items is discouraged by Unity. Imagine if every package that you used created their own menu. It would be total chaos.

Menu Validation Methods

A menu item can have a validation method. The validation method tells Unity whether the menu is enabled or disabled. It applies to all the menus that we discuss further on.

Let’s create a validation method for our menu from before. Add this code to the MyMenus class from before.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Now in Unity, our menu item is grayed out and cannot be pressed.

Normal Menus

File, Edit, Window and Help are normal menus. They can only be reached from the top menu bar. As we will see later, some menus have special handling and can be accessed from other editor windows in Unity.

Window menu is for showing Editor Windows. We will learn about Editor Windows in the next post. But imagine if we had created a tool like mecanim or asset store or animation panel. We would create a dockable window within Unity for the user to perform tasks. The normal way to show it would be through the Window menu.

For now, we can add a menu item to the Window menu that does the validation. Unity Editor doesn’t check if we actually go with the convention of showing an Editor window. But don’t do it for real assets / packages you make.

Add this code to the MyMenus class from before.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Note that our menu item shows last. This is because we set the priority to 10000 which is really high. Let’s reduce the priority to 10.

Unity doesn’t update the menu if only the priority changes. You need to comment the line with the MenuItem attribute, switch to Unity to have the menu item removed and then uncomment the line again.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Now our menu item shows near the top. You have to play around with different values to get your menu item where you want it.

Help menu is for showing references to different learning material. Nothing new here. As an exercise you can add an item that does validation to this menu as well.

GameObject Menu

This menu is special. It is for adding new game objects to your scene and changing the scene hierarchy.

We can add menu items to this menu just as we did before. Items with priority 10 will also show in the hierarchy window’s context menu and create button.

This time instead of validation, let’s create a new game object with our TargetController script already added to it.

Add this code the MyMenus class from before.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Assets Menu

Assets menu is for creating and managing assets in the project. The items under the Create sub menu will also show in the Project window’s context menu and create button.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

CreateAssetMenu attribute

For creating instances of our scriptable objects, we can use the CreateAssetMenu attribute which will add an entry to Assets/Create menu for us. It handles creating the new asset in the selected folder in the Projects window.

Create a new file named MyScriptableObject.cs under your scripts folder with this code.

Now we can create instances of our Scriptable Object from the Assets/Create menu, which shows as context menu and from the + button in the Projects window.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Component Menu

Component menu is used for adding new components to Unity objects. At this point you should be comfortable adding an item to this menu the normal way using the MenuItem attribute.

Our MonoBehaviours normally end up under the Scripts/ / path. So we can actually add our custom scripts to our objects.

AddComponentMenu attribute

AddComponentMenu attribute can be used with our component to create a custom path for our component in the Component menu.

Let’s add this attribute to our TargetController class.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Context Menus in Inspector Window

We can add menu items to Inspector window’s context menu for different components. Let’s go ahead and add a menu item to the context menu for our GameManager component.

Now when we right click the header of the Inspector UI for our component, we have the Validate Scene menu item.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

We are not limited to our components only. We can create a new context menu item for Unity’s Text component.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Pressing the menu item will set the font size of this text component to 36.

Conclusion

In this post we learnt about:

If you have any questions and suggestions about this post, feel free to leave a comment.

If you find this tutorial useful, please support me on Patreon. It takes a good amount of time to write these tutorials and your support will keep me going. Thank you!

In the next post, we will see how to create custom Editor windows.

Full Unity 2D Game Tutorial 2019 – Main Menu

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Sharing is caring!

Full Unity 2D Game Tutorial 2019 – Main Menu

In this part of the tutorial we will be crating the main menu and adding some buttons to allows us to play a game, go to the options menu and to exit the game.

Full Unity 2D Game Tutorial 2019 – Scene

We have our game scene but its just called SampleScene. Let’s fix that by right clicking on the scene in the project window and renaming it to GameScene. While were here right click and add a new scene and name it MainMenu.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Now save your GameScene and select the background and AudioManager objects in the hierarchy view and right click > copy. Open the new Main Menu scene and paste the objects. We now have music and a background in our main menu. We can now focus on making the UI.

Full Unity 2D Game Tutorial 2019 – Menu UI

The first thing we are going to do is to add a button. This will not only create the button but also the Canvas and Event System. Rename it to StartButton.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Now we have a canvas let’s set it up so it work’s on multiple display sizes. First set the UI Scale Mode to Scale With Screen Size. then set the size to 1024 x 768. This is a small 16:9 aspect ratio and should allow us to work on a multitude of displays without too many issues.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unityThe Canvas is done for now so lets setup the main menu. We have our button but its just there floating around inside the canvas. We need more order, so add an empty game object to the canvas and name it Main Menu. This will be the object that holds all our main menu UI. The reason we do this is so we can swap between menus by deactivating the main menu and showing the options menu and vice versa. Move the StartButton inside the Main Menu object.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unityOur menu is now nice and ordered. Now we can play with the style.

Full Unity 2D Game Tutorial 2019 – Menu Style

The MainMenu object at the moment is just a small square area inside the canvas. Use the Anchor Presets to fill the entire canvas with the MainMenu by Shift+Alt clicking the bottom right icon. This will fill the canvas with our menu. On the MainMenu object add a new component called Vertical Layout Group. This will layout our objects for us and keep things displaying neatly in a vertical line. We set the Child Alignment to Upper Center so all our buttons will be laid out in the middle of our screen starting from the top.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

The size of our canvas and main menu have been set but our button hasn’t. Lets set its size to 400 x 75. The original text element isn’t as good as the TextMeshPro text so delete the current text and replace it with a TextMeshPro text. Set the text to Start and change the size to say 64. That should be big enough. The TextMeshPro text doesn’t automatically fill the start button size, it actually is larger than the button by default so use the Anchor presets again to fit the button with the same Shift+Alt clicking the bottom right icon we did before.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

We should now have a big ugly white box in the center of our screen. Let’s fix that by adjusting the button colours. The image below shows how I have set mine. Pure black for normal, a tint of blue for highlighted and a dark grey for pressed all set with 80 alpha.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Full Unity 2D Game Tutorial 2019 – TextMeshPro Text Style

The button looks better but the text is still rather boring. We’re going to fix that by using a colour gradient for TextMeshPro. Create a folder called TMPResources and right click Create > TextMeshPro > Color Gradient and name it MenuGradient. Adjust the colours to something you like. I went with a fire orange > red like the image below.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unityTo apply this gradient to your text you will have to check the Color Gradient box and drop the gradient you made into the colour preset box.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unityWe have finished creating the style for the button, so now we duplicate it and make another 2. Select the StartButton in the hierarchy window and using the ctrl+d shortcut to duplicate it. Do this twice to create a total of 3 buttons. Rename all your buttons and button texts so we have a start button and options button and an exit button. You should end up with something like this:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Full Unity 2D Game Tutorial 2019 – Responding to Button Events

Add a new component to the MainMenu object and create a new c# script called MainMenuController. This will house all the code for our buttons. Then in that script add this code:

Code Notes:
using UnityEngine.SceneManagement has been added as we will be switching scenes to the game scene.
Application.Quit() will quite the game when not run in the Unity editor.

We have added 3 methods. One for each of our buttons. The options method will be blank until we add an options menu and start adding Preferences. How do we link this buttons to these methods we created? Each button has an On Click section in the Inspector. Here we first click the + icon to add a new action. Then we drag and drop the MainMenu object into the bottom box. This say that this object has the methods we want to run when this button is clicked. We then click the No Function drop down menu and scroll to our MainMenuController script and select the appropriate method. Repeat these steps for the other 2 buttons and we have our menu up and working.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

All the buttons should now call their respective methods and allow us to play the game. We won’t be able to test the exit button because unity wont exit the game when run in the unity editor, however it will close when we create a build. You’ll just have to trust me on that.

There’s on Last thing I want to do before we move on to the Options menu and that is to create a title. We already have a nice Text object inside our buttons so we will just copy one of those. Duplicate one of the buttons Text objects and drag it out of the button and into the menu. Set the Rect Transform width to 600 and the height to 75 and give it a nice title by setting the text. You should end up with something like this:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Full Unity 2D Game Tutorial 2019 – Options Menu

I have chosen to do both the Main Menu and the Options in the same scene as not to duplicate scene data like the audio manager, canvas background etc. We will implement a toggle system that toggles the Main menu of and the option menu on. First we will duplicate the whole MainMenu and call it OptionsMenu. This will contain the title, all its buttons and the Main Menu Controller. We don’t need the Main Menu Controller on our OptionsMenu so delete that one so we only have the one on the MainMenu Controller.

We will now update out MeinMenu code to allow use to swap between the main menu and the potions menu.

Code Notes:
SetActive(true/false) this is used to enable or disable a game object. it will enable or disable all of its children too.
Added a back method so we can go back from the options menu to the main menu.

We are currently showing both the main menu and the options menu at the same time. This will make it difficult for us to see what were adding or removing from the options menu. So for now lets just disable the Main Menu by unchecking the check box shown in the image below:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

We should now only be able to see the options menu. First, we will remove the Start and Options button in the options menu as we will not be using these. We will however keep the title and Exit button. We will Change the names of the object and text so it is a Back button. Then we will replace the On Click function to the back method we created to the back method we created in our MainMenu script.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Full Unity 2D Game Tutorial 2019 – Options Menu Sliders

We will now implement a slider which we will use to control the volume of our music. As usual create an empty ojbect to hold our slider and call it MusicVolumeSlider. Then add a slider component. Create > UI > Slider.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unitySet the MusicVolumeSlider width to 400 and height to 50. This should give use a nice visible size and select the Slider and use the Anchor presets to fill it parent (shift+alt+click bottom right). Its still ugly and has an odd shaped handle. We will not be using the handle so we can just disable this with the checkbox(same as we did for the main menu) with the Handle Slide Area disabled we can make some adjustments to make it look better.

Adjust the slider value field to 0.5. This should set our sliders bar half way through the slider so we can see the background and fill colours.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unityNext we set the background colour. I set mine to #FF0000 with an alpha of 123. This gives us a semi transparent background with a hint of red. The next part is to adjust the Fill Area Rect transform. Set the Left, Top, PosZ,Right and bottom to zero. This makes the fill area match its parent exactly. so it will fill properly with no border or spacing.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Next we adjust the Fill. Set the Left, Top, PosZ,Right and bottom to zero and select a colour you want for the bar that fills up the slider. We need one more thing for the slider, a descriptive text so users know what this slider is for. We will duplicate the Title TextMeshPro text and place it inside our MusicVolumeSlider object. Change the size down to something like 20 and move it into position above the slider. You should end up with something like this.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Right now our options for volume doesn’t do anything. We will implement the preferences in the next section of the tutorial. Our Main menu script now expects the Main menu and option menu. So add these and disable the option menu and enable the Main menu. You should now have something that works similar to this gif.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

That’s it for this part of the tutorial. In the next part we will go over adding some functionality to our options menu including duplicating the music volume to create an effects volume control. As usual the source is available here on Github.

Как создать внутриигровое меню в Unity

Создание и дизайн главного меню и меню настроек

1. Создаем две сцены: Menu и Game
2. Открываем File->BuildSettings и перетаскиваем созданные сцены в Scenes in build.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Теперь можем приступать к созданию пользовательского интерфейса. Откройте сцену Menu и добавьте Panel. Сразу добавляется Canvas(Холст) и дочерним объектом к нему добавляется Panel (Панель).

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Обратим внимание на инспектор для Canvas. А именно на компонент Canvas.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Render Mode автоматически выставлен на Screen Space – Overlay.

Screen Space – Overlay:

Способ рендеринга, при котором Canvas напрямую привязан к экрану. Если изменить разрешение экрана или размер, то Canvas с такой настройкой тоже изменит свой масштаб на подходящий. UI в таком случае будет отрисовываться поверх других объектов.

Важен порядок размещения объектов в иерархии. Холст Screen Space – Overlay должен находиться в самом верху иерархии, иначе он может пропасть из виду.

Screen Space – Camera:

В таком случае, Холст прикрепляется в камере. Для такой настройки обязательно нужно указать камеру которой соответствует Холст. Как и в предыдущем пункте, Холст будет менять свой масштаб в зависимости от разрешения и размера экрана, а также от области видимости камеры.

Так же для Холста с такими настройками важно размещение относительно других объектов. На переднем плане будут объекты, которые находятся ближе к камере, не зависимо от того, это UI или другие GameObjects.

Холст размещается, как любой другой объект без привязки к камере или экрану, он может быть ориентирован как вам угодно, размер Холста задается с помощью RectTransform, но то, как его будет видно во время игры, будет зависеть от положения камеры.
В данном задании мы будем использовать Screen Space – Overlay.
Давайте настроим цвет панели. Можно также добавить картинку на фон. Для этого нужно обратить внимание на компонент Image в Инспекторе панели.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Как видите, картинка добавляется в поле Source Image. Картинку можно просто перетащить из файлов проекта, либо кликнуть на кружочек справа от поля.

Цвет выбирается в поле Color, либо с помощью инструмента пипетки.
Важно знать, что пипетка позволяет выбрать цвет за пределами Unity.
После того, как выбрали цвет или картинку, нам нужно разместить кнопки, которые всем будут управлять, а так же текст. Чтобы упростить себе задачу, для Panel мы добавим еще один компонент, который называется Vertical Layout Group. И сразу настроим его.

Нам необходимо разместить все кнопки и текст по центру экрана. Для этого находим в компоненте Vertical Layout Group пункт Child Alignment и выбираем Middle Center. Теперь все наши элементы, будь то кнопки или текст, будут выравниваться по центру, независимо от разрешения экрана.

Так же убираем галочки с ChildForceExpand. Должно получиться так:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Данный компонент можно настраивать в зависимости от того, какой вид вы хотите получить.

В нашем меню должны быть следующие кнопки:

1. Start Game
2. Settings
3. Exit

Сейчас, добавляем Text дочерним элементом нашей Панели. Можете заметить, как он прикрепляется по центру. Иногда для этого требуется созданный элемент в окне Scene просто передвинуть на Panel и тогда он выровняется. Настраиваем текст так, как хочется с помощью компонента Text(Script) в инспекторе.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

После добавляем Button. Кнопка добавится под текст.

Разберем компонент Button нашей кнопки. Нас интересует Transition – то, как кнопка будет реагировать на действия мышки. В Unity реализовано несколько способов. Пока рассмотрим довольно простой Color Tint. Это значит, что кнопка будет менять свой цвет при определенных состояниях. Интерфейс для настройки довольно удобный. Настраиваем так, как нравится.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Так же у объекта Button есть дочерний объект Text – это текст который будет отображаться на кнопке. В тексте прописываем Play.

Кажется, Текст и Кнопки находятся слишком близко друг к другу.

Что бы это исправить для нашего Текста Menu добавляем еще один компонент, который называется Layout Element. И ставим галочку напротив Ignore Layout.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

После этого выставляем Anchor на Middle-Center.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Потом добавляем еще три кнопки и называем их Settings, Credits, Exit.
Можно поменять размеры кнопок. На этом этапе меню выглядит так:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Переходы между main menu и settings

Что бы переходить на меню опций не обязательно делать новую сцену.
Для начала создаем пустой GameObject (Create Empty) как Child нашего Холста. Назовем его Main menu. Потом нашу панель, со всеми инструментами сделаем дочерними элементами этого объекта. Должно получиться так:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Выбираем наш MainMenu объект и сделаем его дубликат. С выбранным элементом нажимаем комбинацию клавиш Ctrl+D. У нас появится новый объект.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Переименовываем новый объект в Settings. Для удобства управления инактивируем MainMenu.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Дальше в панели Settings переписываем текст на Settings, а так же удаляем все кнопки.
В настройках мы сделаем следующее – Fullscreeen, настройки громкости, качество изображения, разрешение экрана.

За контроль Fullscreen будет отвечать элемент Toggle.
За громкость – Slider.
За качество изображения и разрешение – Dropdown.

Между каждыми элементами следует разместить текст, который будет обозначать название каждой настройки. Следует также добавить кнопку, которая будет возвращать нас обратно в главное меню.

Можно настроить Spacing в Vertical layout group, чтобы между элементами было немного пространства. Добавим на панель картинку и в итоге получим такой результат:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Программирование кнопок

Перейдем к написанию скрипта меню.

Нам нужно, чтобы по нажатию кнопки Play у нас запускалась другая сцена с нашей игрой, а по нажатию кнопки Exit игра закрывалась.

Это мы и пропишем в нашем скрипте.

Для MainMenu добавляем новый компонент MenuControls.cs и отрываем его.

Первое что надо сделать – удалить существующие методы Start() и Update() – тут они нам не нужны.

Дальше нам надо подключить следующее:

После этого напишем свой метод для нажатия кнопки Play. Метод должен быть public — нам нужно иметь возможность видеть его за пределами нашего скрипта.

За загрузку сцены отвечает SceneManager и у него есть метод LoadScene. Существует несколько перегрузок метода. Можно передавать имя сцены, которую вы хотите загрузить. В нашем случае это сцена «Game».

В итоге функция будет выглядеть следующим образом.

Так же создаем метод для выхода из игры:

Однако в Unity мы не увидим результата работы этого метода, так как подобное работает только в билде. Для того что бы проверить, что все работает правильно, добавляем в метод строчку

Теперь необходимо прикрепить события кнопок к этим методам. Выбираем кнопку Play и находим в инспекторе следующее:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Это событие кнопки, которое по нажатию будет вызывать подписанные на событие методы. Добавляем метод нажимая на +.

В появившееся окно нужно перетащить объект, в котором содержится нужный скрипт. В нашем случае это Main Menu.

После этого нужно выбрать скрипт MenuControls и найти метод PlayPressed().

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Точно также делаем для кнопки Exit. Только теперь выбираем метод ExitPressed().
Для кнопки Settings нам не нужно писать никакой код, так как некоторый функционал уже встроен.

Суть в том, что мы будем активировать GameObject. На этом этапе у вас должен быть активным MainMenu, а Settings не должно быть видно. Так же видим, что когда мы активируем Settings, он полностью перекрывает Menu. Суть в том, что играет роль порядок расположения дочерних объектов Холста – в каком порядке они расположены в иерархии в том порядке они и будут прорисовываться. Поскольку Settings у нас находятся над Main Menu, то они перекрывают меню.
Это мы и будем использовать.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Ну а для кнопки Back, которая находится в меню опций, можно таким же образом подключить событие SetActive для объекта Settings, но на этот раз нам нужно инактивировать наш объект, поэтому мы просто не ставим галочку.

Вот и все, мы закончили создание меню, а в следующей части продолжим и сделаем так, чтобы игра реагировала на изменения настроек.

Настройки

Настройки полного экрана

Первое что мы пропишем это переключение полноэкранного и оконного режимов.
Нужно убрать галочку с пункта Is On нашего Toggle элемента.
Создаем скрипт для объекта Settings. Назовем его Settings.cs.

Для начала нам надо хранить переменную типа bool которая будет отображать текущее состояние – полноэкранный режим или нет. А потом, по изменению toggle эта переменная будет переключаться на противоположное значение.

У экрана есть свойство Screen.fullScreen типа bool. Можно просто будем присваивать значение нашей переменной isFullScreen этому свойству.

Код выглядит так:

Увидеть результат можно только в билде. Давайте сейчас это сделаем. Учтите, что для того что бы билд был правильным нужно оставить активным только объект MainMenu, а Settings отключить. Если это сделано, то запускаем билд через File->BuildSettings и нажимаем кнопку Build.

После этого можно проверить работу программы. Если все правильно, то по нажатию галочки сразу будет изменяться режим.

Изменения громкости звука в игре

Для работы с настройками звука нам для начала понадобится AudioMixer, а также какой-нибудь трек, на котором мы будем проверять работу наших настроек.

Называем его GameSettings. После этого открываем окно AudioMixer: Window->Audio Mixer (Ctrl + 8).

Что бы контролировать параметры миксера через скрипт, их нужно сделать видимыми для этого скрипта. Эта процедура называется ExposeParameters. Для этого кликаем на Mixer и в инспекторе находим volume и кликаем правой кнопкой мыши. Выбираем Expose to script:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Теперь в окне Audio Mixer обратите внимание на пункт Exposed Parameters в верхней левой части.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Теперь там есть параметр. Кликаем на него и называем наш параметр masterVolume. Следует запомнить имя, которое ему присваиваем – его нужно будет указать в коде.

Переходим в Settings.cs и создаем поле AudioMixer, чтобы получить ссылку на него в коде.

потом создаем метод

Метод SetFloat будет принимать значения нашего слайдера и присваивать это значение параметру “masterVolume”.

Осталось прикрепить наш метод к событиям слайдера. Находим в инспекторе слайдера поле On Value Changed и точно так же прикрепляем объект. Вот только теперь нам надо не просто выбирать метод из списка, а использовать поле Dynamic float. Как видите, там уже есть наш метод, и он будет получать переменную от самого слайдера. Также нужно не забыть перетащить AudioMixer в соответствующее поле в компоненте Settings.cs.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Теперь добавим звуки в нашу игру, чтобы проверить работу скрипта.
На canvas добавим компонент Audio Source.
Настроим его следующим образом:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Audio Clip – саундтрек
Output – Мастер нашего миксера (дочерний объект)
Loop – поставить галочку – зациклить композицию, чтобы она играла постоянно.

Качество изображения

В Unity уже встроены настройки качества изображения. Edit->Project Settings->Quality. В инспекторе видим Quality settings. Их можно добавлять и настраивать.

Особенностью работы с настройками качества является следующее:
Каждой настройке соответствует индекс, который мы можем получить из Dropdown. Все что нужно сделать – переписать соответствующие пункты в нужные индексы в нашем UI элементе. Открываем его и в инспекторе находим Dropdown(Script) и в нем пункт Options. Дальше вписываем настройки в нужном порядке. У меня получилось так:

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Дальше нужно прописать код. Мы продолжаем дополнять методами наш скрипт Settings.cs
Создаем метод, который будет принимать int – индекс выбранного пункта.

Сохраняем скрипт и подключаем метод к событию на нашем меню. На этот раз это событие Dropdown – On Value Changed.

Поскольку наш метод будет получать значение от самого UI элемента, то мы выбираем название метода из группы Dymanic int. по аналогии с предыдущим пунктом.

Разрешение экрана

Экраны у всех разные и наперед угадать какие разрешения на них будут поддерживаться невозможно. Поэтому для настроек разрешения экрана нужно сначала получить все возможные разрешения, а потом заполнить список разрешений этими значениями.

Первое что нам понадобится – массив типа Resolution[] где мы будем хранить значения разрешений экрана.

Однако для пунктов выпадающего списка тип – string. Поэтому создаем список List<> в который мы будем сохранять значения возможных разрешений. Для работы со списками необходимо подключить:

Также нам понадобится ссылка на соответствующий Dropdown. Для работы с UI элементами следует также прописать:

В скрипте получим следующие поля:

Инициализацию и заполнение проводим в методе Awake. Этот метод вызывается при запуске объекта, соответственно выполняется раньше, чем все остальные методы.

Получаем значения и каждое из них добавляем в List в формате ширина*высота. После этого очищаем список Dropdown и заполняем его новыми опциями.

Теперь нужно создать метод, который будет менять разрешение экрана. Как и в предыдущих пунктах – принимать значение будем от UI элемента. Создаем функцию, которая принимает int

В SetResolution необходимо передать параметры – ширина, высота и булевскую переменную, отвечающую за полный экран. У нас такая уже есть – это isFullScreen. Передаем ее в функцию.
Дальше не забываем подключить к соответствующему событию наш метод Resolution из группы Dynamic Int, а так же добавить ссылку на нужный Dropdown.

How to make menu in unity. Смотреть фото How to make menu in unity. Смотреть картинку How to make menu in unity. Картинка про How to make menu in unity. Фото How to make menu in unity

Готово. Теперь можно использовать это меню вместо скучного дефолтного лаунчера. Однако, чтобы был толк нужно отключить его запуск.

Edit->ProjectSettings-> Display Resolution Dialog-Disabled

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *