Press "Enter" to skip to content

Первые шаги в Unity

Так с чего же начать работу на Unity и реализацию своего проекта?

Unity3D Tutorial

Unity 3D is a powerful game development engine. It is cross platform that is it allows you to create games for mobile, web, desktop and console, around 30 platforms in all. Unity 3D has many exciting features, a few of them are given below:

  • Cost: Unity 3D’s personal version is free of cost for beginners, students and hobbyists. Unity Personal has all the core features of Unity. It also has core analytics, cloud build, ads, multiplayer, in-app purchases and cross platform features. Other than these features Unity personal has a few limitations too. Two other versions Unity Plus and Unity Pro are also available for serious creators and professionals, starting at the price of $35 per month.
  • All In-one Editor: Unity is known as an all in one editor. The Unity editor has multiple artist friendly tools for designing impressive experiences. It has a strong suit of developer tools for implementing game logic and high end performing gameplay. Unity also allows you to create both 2D and 3D games. It also includes AI pathfinding tools based on a navigation system. It has an excellent built-in system to create eye catching user interfaces. Its Box2D physics engine allows us to create realistic motion, momentum, force and gameplay.
  • Platforms: Unity supports many different platforms like Linux, IOS, Android, Windows, etc. totally nearly 30 platforms.
  • Virtual and Augmented Reality: Unity supports for virtual and augmented reality development. It is most widely used engine for XR development. It has Microsoft HoloLens, Stream VR/Vive, Gear VR and PlayStation VR support in Unity Plus for virtual and augmented reality.
  • Multiplayer: For real time networked and multiplayer games Unity is the best option. It provides servers for real time collaboration.
  • Engine Performance: Unity’s engine performance is extraordinary. Multi-threaded compute system is coming for intensive scenarios. Unity engine has advanced profiling tools which determines if your game is CPU bound or not and also tells how to optimize it with better experience.
  • Unity Asset Store: It is a massive catalog of free and paid content. You can increase your development time by downloading many built-in free models and assets. Even Unity asset store has complete projects both for free and paid.
  • Graphics Rendering: Unity has one of the best graphics rendering system. It allows you to create environments like luminous day, gaudy glow of neon signs, dimly lit midnights and shadowy tunnels. It produces amazing visual effects. Although Unity supports multi-platform but still it tries to cover low level graphics API of every platform for better results and smother user experience.
  • Team Collaboration: It has features that enable collaboration and simple workflow. Unity’s cloud storage allows you to save, share and sync your projects anywhere.
  • Performance Reporting: Unity performance reporting system deals with issues in real time. High priorities issues are solved very efficiently. Finds application errors across devices and platforms.

Unity Interfaces

Let’s explore Unity editor’s interfaces, which are configurable. It is made up of tapped windows that you can rearrange according to your need. Let’s explore the default window settings. Here is the image how it looks

Hierarchy Window

The Hierarchy window represents every object in the scene. It shows how objects are linked with each other in the scene, so these two windows are related. In hierarchy window there is a drop down list named as Create. You can create an empty object, 3D objects, 2D objects, light, audio, video, particle system and camera objects very easily. The hierarchy window is shown below. ‘Untitled’ is the name of the scene. You can rename it as you want. You can see a drop down icon at the very right side of untitled (scene name). By clicking on this drop down you can see different options for Save Scene and Add New Scene.

Scene Window

Scene window is where you create your scene. It is where you can interact with your game objects and models. You can resize, reshape and reposition your scene objects. This is the window where you start working with Unity. Scene view can be 2D or 3D depending on the setting of your project. Here is a screen shot of how the scene window looks:

In scene window you can see another tab labeled Shaded, this is where you can select what type of view you want either shaded or wireframe. It has many other options like Miscellaneous, Global illumination, Real time GI, Baked GI and many others. You can view to 2D or 3D by using the button next to the Shaded drop down. Next is the toggle button for scene lighting. Similarly a toggle button for scene audio. Next is a drop down list to enable sky box, fog, animated material and image effects.

Game Window

Game window represents your final, published game in play mode. It is rendered from the cameras you used in your game. In game window you can see another tool bar as shown below in the screen shot:

Display 1 shows camera present in your game scene. By default it is set to Display 1 for main camera. If you have multiple cameras and you want to switch then you can select from drop down list. Next to this you can see a drop down for aspect ratios. You can select according to your target device monitor screen. Next you can see a Scale slider to zoom in. Scroll to the right and examine more details of your scene in play mode. Next is the button for Maximize On Play, when clicked, the game window size will be maximum on play mode. Mute Audio toggle is used for mute/unmute audio. Stats shows rendering statistics about your game’s audio and graphics.

Project Assets Window

As the name shows assets window has all the assets of your project which you can use. If you import something new it will appear in project assets window. Project asset window has two parts, the left panel and right panel as shown in the below screen shot:

Left pane shows the hierarchical structure of the project’s assets. When you click on any folder it will show the details in the right panel. For example in the given figure Prefabs folder is clicked in left panel so its details are showing in the right panel as it contains two game objects. In the left panel you can see a Favorites section, where you can drag items which you want to use very frequently to avoid time waste in searching for them. Above it you can see a Create drop down which enables you to create a C# script, a folder, a shader, a GUI skin, a scene, a prefab, a material and much more.

Console Window

Console window is the place where you can see your errors, warnings and messages. You can adjust them by clicking their toggle buttons. It also allows you to clear all the errors, warnings and messages. You can pause errors for a certain time. Here you can see in the following figure

The drop down icon at the very top right corner has options for Editor Log and Stack Trace Logging.

Inspector Window

Inspector window is one of the most interesting and useful window of the editor. It is the place where you can edit all the properties of the selected game object. Every game object has its own type so their properties will be different and inspector’s window can vary. Assets, scripts and game objects all vary in properties. Lets see the properties of a cube in inspector window. Here is the image:

You can rename your game object by just clicking on the previous name and typing a new one. Next you will see the transform section where you can adjust position, rotation and scaling of your selected game object. In the last you see a button name as Add Component, click on it to add new components to your game object, for example if you want to attach a script, just click on add component and type your script name.

Tool Bar

Last is the tool bar tab, it has many useful features. It contains some basic tools for manipulating the scene view and objects. In center there are buttons for play, pause and step control. The next two buttons shows your Unity cloud and Unity account. Here is the figure how it looks:

Getting Started With Unity

Let’s start creating a new project in Unity because it’s time to play with what we have learned. Double click on Unity icon following window will appear:

Enter Project Name, select a workplace Location and then select type of your project either 2D or 3D. Click on Create Project.

By default you will see an untitled scene containing a main camera and directional light in the scene. Let’s start creating an environment.

Building Environment

First of all create a plane by clicking on Create -> 3D Object and then select Plane. Or alternatively you can create it by clicking on GameObject -> Game Object and then select Plane. Go to hierarchy window and click on plane game object. Now go to inspector window and rename it as Ground. Now adjust transformation values so that this plane looks like a straight road. Just scale X to 6 and Z to 50. Here is the image how it looks

Now download a road texture and apply it on the ground object. Create a folder name as Texture. Drag downloaded road texture to Texture’s folder. Now select Ground and drag road texture in the scene view. Here is the image how it looks

This is the texture I downloaded

After applying texture on the ground, click on Ground and set tiling in inspector window. Here is how I set it.

Now you have created a road model, let’s create a ball model in unity.

Go to Create -> 3D object and then select Sphere, you will see a sphere object in scene window. Select it and go to the inspector window to rename it as Ball. Now adjust transformation values accordingly. Just scale it to 5 along all three axis and reposition it to the center of the road. Here is how it looks

Now create a fence or wall around the road.

Go to Create -> 3D Object and then select Cube. Select it and rename it to Wall1. Go to inspector window and set transformation values so that it looks like a wall around the road. Here is how it looks:

See these transformation values for Wall1. Scale Y to 6 and Z to 500. Then adjust its position so that it comes at the corners of road.

Now search for a wall texture download it and copy to the Texture folder in assets. Drag wall texture to the wall in the scene window. Adjust tilling so that it looks nice and smooth. I adjusted tiling as X to 50 and Y to 1.5. After adjusting tiling this is how it looks

This is the texture I used for wall

We have created wall for one side of the road. Now do the same thing for the other side of the road too. Instead of going through the all the process we can just copy Wall1 and rename it to Wall2.

Select Wall1 in hierarchy window and then right click and then select Duplicate option. It will create another game object having same size and transformation values. Click on Wall1(1) and rename it to Wall2. Now adjust position so that it comes to the other corner of the road.

See the following image how cool it looks

My position values for Wall2 are X to -29.6 Y to 2.6 and Z to 2.6.

Now create a material for Ball. Go to Project window and create a folder by right clicking on the mouse and then select Folder. Name it as Materials. Again right click on mouse and create a material. Name it as redBall. In inspector’s window select color of material. Go to Main Maps and select Albedo color to red. Increase the metallic texture by scrolling bar to the right. Drag this material to the Ball in the scene view. Here is how it looks

Here is how material looks:

So we are done with our environment development. Now time to do some coding. For this we have to create a script.

Scripting in Unity

To implement your own gameplay features and to control the behavior of the game Unity provides as a scripting mechanism. You can write your own script for the desired output of the game. With these scripts you can trigger game events, can change component’s properties and you can respond to user inputs. Basically Unity supports two different programming languages for scripting purpose, one is C# and other is JavaScript. Other than these two languages many other .NET languages can also be used with Unity. Scripts are known as behavior component in Unity.

Creating a Script

Let’s start creating a Unity script. For this go to the assets window and create a new folder named Scripts (you can skip creating new folders for every new type of asset but its good practice to keep things organized). Here is how my assets window looks now:

Now open the Scripts folder, right click, then go to Create and select C# script. Rename script to Movement. We are creating this script to move and roll the ball on the road. For now the ball is stationary, doing nothing, let’s create some movement in it.

Double click on the Movement script it will open in Mono Develop. If your script is a mono behavior then you will see some pre written code like this

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovementScript : MonoBehaviour

// Use this for initialization
void Start ()

// Update is called once per frame
void Update ()

You can see two functions Start() and Update().

Start(): Start function is used for initializing variables and objects. It is called only once when the script is enabled just before any other update function calls.

Update(): It is a mono behavior function, it is called once in every frame.

Other than these two there are many other mono behavior functions for example awake(), fixedUpdate(), lateUpdate() etc.

To move the ball on the road first of all you have to make it a rigid body (it is an ideal solid body in which deformation is neglected). Select Ball in hierarchy window and click on Add Component button in inspector window. Type rigid body and press Enter. A rigid body will attach to the Ball. Now go to script and create a private variable of type Rigidbody. Now assign rigid body of the Ball to this variable you just created in the script.

private Rigidbody rb;
rb = GetComponent ();

Now write some code for the movement of this rigid body. What’s the idea? Ball should move when I press arrow keys of the key board. It should move forward when up key is pressed, backward when down key is pressed and so on.

So the input in coming from the keyboard, how should I get this input? Unity’s Input class has a function name GetAxis(), to returns the value of virtual axis identified by the axis name. Create two variables one for x-axis and one for y-axis input. Here is how it should be

float moveHorizontal = Input.GetAxis (“Horizontal”);

Now create a Vector3 variable to get movement values.

Vector3 movement = new Vector3 (moveHorizontal, 0.0f,moveVerticle );

First parameter is the value of x-axis, second is the value of y-axis and third is the value of z-axis. As ball will not move in the direction of y-axis so assign zero to it. Lastly add this movement to rigid body and multiply with a constant number for speed or create another variable for speed. See the complete code below

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour

public float speed;
private Rigidbody rb;
// Use this for initialization
void Start () rb = GetComponent ();
>

// Fixed Update is called after fixed number of frame
void FixedUpdate () float moveHorizontal = Input.GetAxis(“Horizontal”);
float moveVerticle = Input.GetAxis(“Horizontal”);
Vector3 movement = new Vector3 (-1*moveHorizontal, 0.0f,-1*moveVerticle );
rb.AddForce (movement * speed);

As speed is a public variable so you can assign value in the inspector window. Attach this script to the ball by dragging it to the inspector window or by pressing Add Component button. Press play button and test your coding either ball is moving or not.

Setting Camera

Last thing you will notice is when you press forward button and ball starts moving it goes out of the camera as camera is stationary. What should we do? We should move camera too? Yes it is the simplest thing to do. Make the camera child of the ball by dragging main camera to the ball.

Conclusion

This was a basic introductory tutorial in which you learned many interesting features, environment building and scripting in Unity. Don’t hesitate, start creating your first game with Unity today and enjoy!

About the author

Admin

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.

Первые шаги в Unity

Привет, Хабр. Материал подготовлен для тех, кто только начинает осваивать unity.

Unity — это один из самых популярных движков на данный момент. Составить ему конкуренцию может разве что Unreal Engine 4, но что у первого, что и у второго есть свои плюсы и свои минусы. Unity поддерживает почти 30 платформ, в их числе мобильные, виртуальная реальность, настольные компьютеры, консоли и так далее. Unity — это не просто хороший вариант для старта, это идеальный вариант для старта! Тут заложено использование гибкой модульной системы при создании сцен и персонажей в игре. Даже новичок способен создать крутой проект, используя готовые спрайты и конструктор движка.

Если же считаете, что готовы погрузиться с головой в «кирпичную систему» для продвинутых, то тут есть возможность настройки практически любого компонента. К примеру, разработка своего собственного шейдера или же переписать сетевой стек для потребностей своей игры.

Так с чего же начать работу на Unity и реализацию своего проекта?

Первым шагом будет установка ПО. На официальном сайте есть четыре разных версии программы для установки. Какую же выбрать? Всё по порядку. Версии представляют собой одинаковые функции движка.

Если вам интересно, вот что означают эти три варианта:

  • Unity Personal: эта версия бесплатна. Однако ваша компания должна зарабатывать менее 100 000 долларов за финансовый год. Еще одна загвоздка в том, что в каждой игре будет отображаться заставка «Сделано Unity», которую нельзя удалить.
  • Unity Plus: эта версия стоит 35 долларов в месяц. Он поставляется с инструментами отчетности о производительности, оболочкой Unity Pro и некоторыми дополнительными функциями. Эта версия требует, чтобы ваша компания зарабатывала менее 200 000 долларов в год, и она позволяет отключать или настраивать заставку «Сделано Unity».
  • Unity Pro: это самый высокий доступный уровень. Он стоит 125 долларов в месяц и поставляется с полезными сервисами Unity, профессиональными надстройками для iOS и Android и не имеет заставки. Ограничения по доходу тоже нет.

Также можно присмотреться к версии Enterprise, где стоимость подписки определяют пользовательские потребности.

Самые явные различия представленных версий — это то, что в Enterprise игры должны начинаться с заставки Unity. А в платных версиях можно удалить или загрузить другую заставку.

Плюс есть довольно интересные сервисы в Unity, к примеру, Cloud Build и Analytics. Естественно, они существуют только в платных версиях.

Также у движка есть свои правила, как можно использовать бесплатную версию. Рекомендую прочитать FAQ .

Для начала работы будет достаточно персональной версии, поэтому нажимаем кнопку «начать». Это приведёт к странице загрузки, нажимаем «принять условия и загрузить». Начнётся загрузка.

Первым установится Unity Hub

Unity Hub — это автономное приложение, которое упрощает процесс поиска, загрузки и управления вашими проектами и установками Unity.

Если вы запустите редактор Unity без установленного концентратора, Unity предложит вам установить его. Если у вас есть лицензия от предыдущей версии Unity, вы можете создать пустой проект из приглашения установки Hub. Если впоследствии вы попытаетесь создать или открыть проект из редактора Unity, Unity предложит установить Hub.

Создание проекта

Чтобы создать новый проект (и указать, в какой версии редактора его открыть), выполните одно из следующих действий:

  • Щелкните кнопку New. В строке заголовка диалогового окна «Новый проект» отображается версия редактора, которую должен использовать проект.
  • Щелкните стрелку раскрывающегося списка рядом с кнопкой «Создать», чтобы выбрать версию редактора, которую вы хотите использовать. Примечание: это раскрывающееся меню доступно только в том случае, если вы установили несколько версий редактора в хабе.

Вкладка “Проекты”

Чтобы просмотреть проекты, которыми управляет хаб, щелкните значок Проекты

Unity хранит проекты на вашем диске и в облаке. Вы можете открывать как локальные, так и облачные проекты, использующие Unity Collaborate , щелкнув имя проекта. Чтобы открыть проект, которого нет в списке, нажмите «Добавить», чтобы найти на своем компьютере папку «Проект».

Изучение интерфейса

Когда ваш проект загрузится, появится экран, заполненный информацией.

Ваш макет, вероятно, будет выглядеть так:

Если нет, нажмите кнопку «Макет» в правом верхнем углу и выберите 2 на 3 в раскрывающемся меню.

Каждый макет состоит из нескольких различных представлений. Вид просто панель информации, которую вы используете для управления. Например, есть представление для размещения объектов в вашем мире.

Вот как выглядит интерфейс, разбитый на отдельные представления:

Чтобы просмотреть список всех представлений, щелкните параметр «Окно» в строке меню.

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

При работе с Unity вы, как правило, захотите преобразовать представления в макет, который идеально подходит для данной задачи. Unity позволяет сохранять макеты для использования в будущем.

В редакторе найдите вкладку «Игра» и щелкните ее правой кнопкой мыши . В раскрывающемся меню выберите «Добавить вкладку», затем выберите «Профиль».

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

Нажмите и удерживайте на вкладку Профили и перетащите его на вкладке Сцена выше.

Как видите, виды можно перемещать, закреплять и упорядочивать. Они также могут существовать вне редактора в виде плавающих окон.

Чтобы сохранить макет, выберите «Окно \ Макеты \ Сохранить макет…» и назовите его «Отладка».

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

При нажатии вы увидите список всех ваших макетов.

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

Организация активов

Новички в Unity могут представить, что вы разрабатываете свою игру от начала до конца в Unity, включая написание кода, создание 3D-моделей и текстур и т. д.

На самом деле, лучше думать о Unity как об инструменте интеграции. Обычно вы пишете код или создаете 3D-модели или текстуры в отдельной программе и используете Unity, чтобы связать все вместе.

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

Представление, в котором вы импортируете и упорядочиваете активы, называется обозревателем проекта. Он имитирует организацию вашей файловой системы.

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

В Диспетчере проектов выберите папку Assets и нажмите кнопку Create. В раскрывающемся меню выберите «Папка» и назовите ее «Модели». Это будет дом для всех ваших моделей. У вас может возникнуть соблазн создать папки и манипулировать файлами в файловой системе вместо обозревателя проекта. Не делайте этого!

Unity создает метаданные для каждого актива. Создание, изменение или удаление ресурсов в файловой системе может нарушить эти метаданные и вашу игру.

Создайте следующие папки: Animations, Materials, Prefabs, Presets, Scripts и Textures.

Ваш обозреватель проекта должен выглядеть так:

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

Примечание. Все снимки экрана в этом руководстве с этого момента будут отображать самые маленькие настройки.

Наконец, вы можете изменить название актива. Например, ваша текущая сцена называется SampleScene. Выберите папку Scenes, а затем выберите файл SampleScene. Имя будет выделено. Один раз щелкните по нему еще раз, и вы напишете новое имя. Измените его на Main.

Вы можете сделать это с любой папкой или активом в Диспетчере проектов.

Если вам интересно узнать подробнее о формате обучения и программе, познакомиться с преподавателем курса — приглашаем на день открытых дверей онлайн. Регистрация здесь.

  • разработка игр
  • разработка игр на unity
  • unity
  • gamedev

Comments are closed, but trackbacks and pingbacks are open.