[UNITY] Атласы спрайтов

n.fridman
19 Oct 202007:54

Summary

TLDRThis video script discusses the concept of sprite atlases in game optimization, explaining how they are large images containing multiple smaller images to reduce the number of draw calls in 2D game rendering. The creator apologizes for a long absence due to transferring colleges and gathering documents. The tutorial covers two methods of creating sprite atlases: Unity's built-in packing and manual creation in graphic editors like Photoshop. It provides step-by-step instructions for both, including enabling sprite packing, creating an atlas, and using the Sprite Editor for manual slicing. The script concludes with tips on organizing sprite atlases for optimal game performance, emphasizing the balance between atlas size and graphic quality.

Takeaways

  • 😀 The speaker apologizes for their absence due to transferring from one college to another and gathering documents for the military enlistment office.
  • 🏫 They mention living far from the city, which limited the time available for creating videos.
  • 📚 Today's topic is about 'atlases and sprites', which are large images containing multiple smaller images, commonly used to optimize games and reduce the number of draw calls per frame.
  • 🎮 In a 2D game, each frame consists of images, and if they are stored separately, Unity will spend one draw call per image, leading to high hardware load and low FPS.
  • 🔄 To demonstrate, the speaker opens a Unity scene and enables frame debugger to show the rendering process of each frame, highlighting the inefficiency of multiple draw calls.
  • 🛠️ Creating an atlas can be done in several ways, including Unity's built-in sprite packing mechanism or manually creating a large image in Photoshop or Illustrator and then slicing it into sprites within Unity.
  • 🔧 The process of creating an atlas in Unity involves enabling Sprite Packer in Project Settings, creating a Sprite Atlas, and locking the inspector to prevent it from opening when selecting images.
  • 🔄 The speaker disables 'Pivot and Size' to prevent Unity from rotating sprites within the atlas, which can help with packing density but may cause sprite contours to overlap.
  • 📈 They show how to drag and drop sprites into the atlas and use the 'P' key to preview the atlas, noting that the frame debugger still shows the same number of draw calls, indicating no immediate performance improvement.
  • 📊 The speaker compares the performance before and after creating an atlas, noting a significant reduction in draw calls, which can improve game performance.
  • 📘 A link to Unity's documentation on the built-in sprite packer is provided for further reading on the tool's features and how to use it effectively.
  • 🖼️ For external atlas creation, the speaker recommends using graphic editors like Photoshop or Illustrator to manually pack images, then import the large atlas image into Unity and slice it into sprites using the 2D Sprite Editor.
  • 🔑 Tips for using sprite atlases include packing all possible sprites that are frequently used within a single screen's view, such as buttons, icons, game elements, character animations, and enemies, to optimize rendering and reduce hardware load.
  • 📏 The ideal atlas size is up to 2048x2048 pixels, balancing between the quality of graphics and the atlas size to avoid excessive texture blurring while minimizing the load on the device.
  • 📝 The speaker concludes with advice on grouping sprites in atlases based on their usage within a single screen and the importance of finding a balance between atlas size and graphic quality.

Q & A

  • Why was the video creator absent for a long time?

    -The video creator was absent due to the need to transfer from one college to another and gather a lot of documents for the military enlistment office, as they live quite far from the city, leaving almost no time for video production.

  • What is the main topic of the video?

    -The main topic of the video is about atlases and sprites, explaining how large images containing multiple smaller images are used to optimize games and reduce the number of draw calls for rendering each frame.

  • How do sprites in a 2D game affect performance?

    -In a 2D game, each frame consists of images. If all images are stored as separate files, Unity will spend one draw call for each image to render, which can lead to a high load on the hardware and a low frame rate (fps).

  • What is the purpose of using an atlas in game development?

    -Using an atlas in game development helps to reduce the number of draw calls by combining multiple images into a single large image, thus optimizing the game and potentially increasing the frame rate.

  • How can you create a sprite atlas in Unity?

    -You can create a sprite atlas in Unity using the built-in mechanism for packing sprites or by manually creating a large image in a photo editor like Photoshop or Illustrator and then slicing it into individual sprites within Unity.

  • What is the 'Pivot' setting in Unity's sprite settings, and what does it control?

    -The 'Pivot' setting in Unity's sprite settings determines the point around which the sprite rotates. Disabling 'Pivot' tracking prevents Unity from rotating the sprites within the atlas, which can be useful for maintaining the layout of the atlas.

  • How does the video creator demonstrate the effectiveness of using a sprite atlas?

    -The video creator demonstrates the effectiveness by showing the frame debugger in Unity before and after creating a sprite atlas, highlighting the reduction in draw calls from 25 to 8.

  • What is the recommended size for a sprite atlas in Unity?

    -The ideal size for a sprite atlas in Unity is up to 2048 by 2048 pixels, as larger atlases can take more time to process and put more load on the device.

  • What are some tips for organizing sprites in a sprite atlas?

    -The video suggests packing all that can be packed, especially what is frequently used within one screen of the game, and organizing atlases in a way that all sprites in the atlas are used on the scene at the time of rendering for optimal performance.

  • How can you manually create and import a sprite atlas in Unity?

    -You can manually create a sprite atlas by packing images into a large image using a photo editor, then importing this image into Unity and using the 2D Sprite Editor to slice it into individual sprites.

  • What is the 'Sprite Mode' setting in Unity's sprite settings, and when should you change it?

    -The 'Sprite Mode' setting in Unity's sprite settings should be changed from 'Single' to 'Multiple' when you want to divide a large atlas image into multiple smaller sprites within the 2D Sprite Editor.

Outlines

00:00

😀 Introduction and Explanation of Atlases and Sprites

The speaker apologizes for a long absence due to transferring from one college to another and dealing with military enlistment documents. They now have time to resume making videos and introduce the concept of atlases and sprites in gaming. An atlas is a large image containing multiple smaller images, used to optimize game performance by reducing the number of draw calls required for rendering each frame. The video will explain two methods of creating sprite atlases: using Unity's built-in packing feature and manually creating a large image in a graphics editor like Photoshop or Illustrator. The speaker also mentions that by combining images into an atlas, the game can be made more efficient, which is demonstrated by a Unity frame debugger example, showing a reduction in draw calls from 25 to 8.

05:02

🛠️ Creating Sprite Atlases Manually and Tips for Optimization

The speaker discusses creating sprite atlases manually using graphic editors and then importing them into Unity. They explain the process of setting up a sprite atlas in Unity, including enabling the 'Sprite Packer' in project settings and creating a new sprite atlas. The video covers how to select and arrange sprites within the atlas, adjusting settings to prevent Unity from rotating the sprites, and using the 'P' button to preview the atlas. The speaker also provides tips on how to pack sprites effectively, suggesting grouping sprites that are frequently used together within the same screen area. They emphasize the importance of balancing the size of the atlas to ensure optimal game performance without compromising graphic quality, and recommend keeping atlas dimensions to a maximum of 2048x2048 pixels for efficient rendering.

Mindmap

Keywords

💡Atlas

An 'Atlas' in the context of the video refers to a large image that contains multiple smaller images within it. It is used for game optimization to reduce the number of draw calls to the graphics API, which in turn can improve performance and reduce the load on hardware. In the script, the creator discusses how using an atlas can reduce the number of frame rendering calls from 25 to 8, demonstrating its efficiency in a Unity game development scenario.

💡Sprites

Sprites are two-dimensional images or animations used in video games. They are the fundamental graphical elements that make up the visual aspects of a game. In the video, the creator explains that sprites are often packed into an atlas to minimize the number of draw calls, which is a key concept for optimizing game performance.

💡Optimization

Optimization in the video script pertains to the process of improving the performance of a game by reducing the computational load on the hardware. This is achieved through techniques such as using an atlas to minimize draw calls, as mentioned in the script, which is a common practice in game development to enhance the frame rate and overall gaming experience.

💡Draw Call

A 'Draw Call' is a request made to the graphics API to render an image or a part of an image. The script explains that having many draw calls can lead to high hardware load and low FPS (frames per second). The use of an atlas is presented as a method to reduce the number of draw calls, thus optimizing the rendering process.

💡Unity

Unity is a cross-platform game engine used for creating two-dimensional and three-dimensional games. In the script, Unity is the software where the creator demonstrates the process of creating an atlas and optimizing sprite rendering. The video provides a practical guide on using Unity's features for game development.

💡Packing

Packing in the video script refers to the process of combining multiple sprites into a single atlas. This is done to reduce the number of draw calls and to optimize the game's rendering performance. The creator discusses two methods of packing: using Unity's built-in mechanism or creating a large image manually in a graphics editor like Photoshop.

💡Frame Debugger

The 'Frame Debugger' is a tool within Unity that allows developers to visualize and analyze the rendering process of each frame in a game. In the script, the creator uses the Frame Debugger to demonstrate the reduction in draw calls after implementing an atlas, showcasing its effectiveness in optimizing game performance.

💡Pivot

In the context of the video, 'Pivot' refers to the point around which the sprites are rotated within the atlas. The creator mentions disabling 'Pivot' rotation to prevent Unity from altering the orientation of the sprites within the atlas, which is important for maintaining the intended layout and design of the game's graphics.

💡Texture

A 'Texture' in the video script is the surface detail of a sprite or an atlas. The creator notes that while textures may appear incorrectly in the Unity inspector, they render correctly in the game, indicating that the issue is with the inspector's display rather than the actual game graphics.

💡2D Sprite Editor

The '2D Sprite Editor' is a feature within Unity used for editing and slicing large images into individual sprites. The script describes using the editor to manually slice an imported atlas into smaller sprites, which can then be used in the game. This tool is essential for customizing sprite atlases that are created outside of Unity.

💡Grid

A 'Grid' in the video script is a layout used when creating an atlas, especially when packing sprites tightly to reduce the atlas size. The creator suggests using a grid for organizing sprites in an atlas, which helps in maintaining a consistent size for each sprite and makes the slicing process more efficient.

Highlights

The speaker apologizes for a long absence due to transferring from one college to another and gathering documents for the military enlistment office.

The video discusses the concept of atlases and sprites, explaining how they are used for game optimization to reduce the number of draw calls for rendering each frame.

An atlas is a large image containing multiple smaller images, which can help in reducing the hardware load and increasing the FPS in 2D games.

The presenter demonstrates the process of rendering a frame in Unity, showing how many draw calls are made for a simple menu.

The benefits of using an atlas are highlighted, such as reducing the number of draw calls from 25 to 8, which significantly improves performance.

The video covers two methods of creating an atlas: using Unity's built-in sprite packing mechanism or manually creating a large image in a graphics editor like Photoshop.

Instructions on how to enable the sprite packer in Unity's project settings are provided.

The presenter shows how to create a sprite atlas in Unity, including locking the inspector window and disabling rotation and scaling for sprites.

A practical demonstration of adding sprites to an atlas in Unity and previewing the result is given.

The presenter explains the importance of using the frame debugger in Unity to observe the rendering process and the impact of using an atlas.

The video provides a comparison between using an external sprite atlas and Unity's built-in sprite packer, discussing the pros and cons of each method.

Instructions on how to manually create an atlas using a graphics editor and import it into Unity are detailed.

The presenter discusses the use of the 2D Sprite Editor in Unity for slicing a large atlas image into individual sprites.

A step-by-step guide on setting up the sprite editor to automatically slice an atlas based on a grid is provided.

The video concludes with advice on how to effectively use sprite atlases, including which sprites to pack together and how to balance atlas size with graphic quality.

The presenter emphasizes the importance of grouping sprites that are used within the same screen and keeping the atlas size as small as possible without compromising quality.

The video ends with a call to action for viewers to support the channel, like, and subscribe for more content.

Transcripts

play00:00

всем привет и хочу сразу извиниться за

play00:03

свое довольно долго отсутствие

play00:05

это связано с тем что мне нужно было

play00:07

переводиться из одного колледжа в другой

play00:09

и попутно собирать кучу документов для

play00:11

военкомата а живу я довольно далеко от

play00:13

города и поэтому времени на видео у меня

play00:15

почти не оставалось но сейчас все в

play00:17

норме и я могу продолжать делать для вас

play00:19

новые видео сегодня хочу рассказать про

play00:21

атлас и спрайтов это большие картинки

play00:23

внутри которых множество других картинок

play00:25

и используются они как правило для

play00:27

оптимизации игры и в частности для того

play00:29

чтобы уменьшить количество вызовов

play00:30

метода отрисовки для рендера каждого

play00:33

кадра каждый кадр любой 2d игры состоит

play00:35

из картинок и если все они хранятся в

play00:37

виде отдельных картинок то на прорисовку

play00:39

каждой такой картинки unity будет

play00:41

тратить один вызов метода дроу

play00:43

графического api

play00:44

большое количество вызовов метода дроу

play00:46

будет гарантировать вам большую нагрузку

play00:48

на железо и соответственно низкий fps

play00:50

но если объединить все картинки в отл

play00:52

астана рендер каждого атласа будет

play00:54

уходить только один для укол чтобы было

play00:56

понятней я открою сцену в unity и включу

play00:59

фрейм дебаг тут можно увидеть процесс

play01:01

рендера каждого кадра в данном случае

play01:03

чтобы от рендерить один кадр этой

play01:04

статичные менюшки и unity нужно 25 раз

play01:07

обращаться к графическому опять это

play01:09

довольно много учитывая то что это

play01:11

менюшка она просто набор картинок то

play01:13

есть некие их анимации эффектов скриптов

play01:15

и какой-либо логики да и в конце концов

play01:16

если мы можем сделать игру более

play01:18

производительные просто упаковав часто

play01:21

использующиеся вместе картинки в атлас и

play01:23

то почему бы и нет

play01:29

создать атлас поэтов можно несколькими

play01:31

способами и самый простой из них это

play01:33

встроенный механизм unity по упаковке

play01:36

spite of либо можно самому сделать

play01:37

большую картинку в фотошопе или

play01:39

иллюстраторе и нарезать ее на отдельные

play01:41

спрайты уже внутри юлить и в этом видео

play01:43

мы рассмотрим оба способа и начнём с

play01:45

самого простого вначале нам нужно

play01:48

включить про питер для этого открываем

play01:49

project settings

play01:50

переходим во вкладку эти дары и в

play01:52

разделе спрайт покер переключаем

play01:54

качельку либо на элвиса на и болт либо

play01:56

на иное будку bells после этого

play01:59

переходим в папку с проектом и клацаем

play02:01

тут правой царской кнопкой мыши и

play02:04

создаем спрайт атлас для примера я

play02:06

назову его юань далее нажимаем на

play02:09

замочек в инспекторе чтобы заблокировать

play02:10

это окно другими словами когда мы будем

play02:13

выбирать картинки у нас не будет

play02:15

открываться их инспектор пока мы не

play02:17

снимем этот замочек далее я отключу и

play02:20

лаура тишин этой tracking отключение и

play02:22

лаура тиша не даст unity поворачивать

play02:25

спрайты внутри атласа а права-то и

play02:27

speaking ты можешь почитать по ссылке в

play02:29

описании там вроде чё то чтобы контуры

play02:31

одного объекта они перекрывали контур

play02:33

другого объекта типа если это и tracking

play02:35

включён то юлить и более плотно

play02:37

размещает объекты внутри атласа но это

play02:39

чревато тем что контур одного объекта

play02:42

могут пересекать контуры другого тут

play02:44

сейчас будут два скриншота со включенным

play02:46

и отключенном то и трекингом вот типа в

play02:48

чем разница теперь мы можем выделить все

play02:50

спрайты которые мы хотим упаковать и

play02:52

перетащить их на надпись яндекс

play02:54

hobbyking и они автоматически добавится

play02:56

в облас теперь нажимаем на кнопку п

play02:58

превью и все атлас готов я хаза почему

play03:00

но в инспекторе ваншота криво

play03:02

отображается то есть у текстурки

play03:03

поехавшие

play03:04

и вообще нет этих отступов это вот

play03:06

именно в инспекторе но в игре всё норм

play03:08

теперь можно снова посмотреть во фрейм

play03:10

дебаггер и тут такой момент то которым я

play03:12

затупил так как ничего не изменилось и у

play03:14

нас утешит 24 бача да и отрисовка

play03:16

каждого кадра проходят абсолютно так же

play03:18

как и до создания атласа спрайтов я

play03:20

погубил где-то минут 10 типа как этой

play03:23

штукой пользоваться потому что до этого

play03:24

я использовал внешне от вас и спрайтов о

play03:26

них дальше видео и по факту нужно было

play03:29

всего лишь нажать на кнопку play и вуаля

play03:31

25 бача изменились на 8 что в три раза

play03:34

меньше и если посмотреть во френд бак то

play03:36

можно увидеть что все кнопки с иконками

play03:38

рендерится за 12 кал в описании к этому

play03:41

видео будет ссылка на

play03:42

а документацию по встроенному в unity

play03:44

упаковщику спрайтов там можно прочитать

play03:46

какая галочка и за что отвечает да и там

play03:49

вообще много всего полезного написано на

play03:50

дальше мы переходим к более привычным

play03:52

они атласа спрайтов это именно внешний

play03:55

атласа то есть потому что я предпочитаю

play03:56

паковать картиночки вручную в

play03:58

какой-нибудь фотошопе или иллюстраторе а

play04:00

в юрий импортировать уже готовы большую

play04:02

картинку и вот как раз таки о том как

play04:03

эту картинку импортировать и как

play04:05

нарезать ее на отдельные спрайты я и

play04:06

расскажу как я говорил ранее атласа

play04:10

spite of можно создавать и за пределами

play04:13

unity

play04:13

из-за того что атласа спрайтов это

play04:15

просто большие картинки для которых

play04:17

множество других картинок не могут

play04:18

создаваться в любых графических

play04:20

редакторах фигу мой иллюстратор

play04:22

photoshop и многие другие от себя могу

play04:24

посоветовать создавать атласов по сеткам

play04:26

для того чтобы при импорте ты знал на

play04:29

сто процентов размер каждой картинки

play04:31

ну или если ты про то ты можешь паковать

play04:33

картинки как можно плотнее чтобы размер

play04:35

атласа получился меньше для того чтобы

play04:37

нарезать атласу на спрайт и нам нужен

play04:39

пакет 2d спрайт если он у тебя не

play04:41

установлен то зайди в птс менеджер вбей

play04:44

в поиск суда спрайты ты пнин стол после

play04:46

этого ты уже можешь переходить к нарезке

play04:48

атласа чтобы редактор понял что эта

play04:50

картинка представляет из себя атлас

play04:52

нужно в инспекторе а поменять ее спрайт

play04:54

mods a single на multiple и ножа тёплой

play04:57

после этого жмем на кнопку с пройдите у

play04:59

нас откроется окно редактора спрайта в

play05:01

котором нам нужно разделить большой

play05:03

атлас на множество маленьких картинок

play05:05

это можно сделать руками просто помещая

play05:07

в рамку каждый из элементов на мы

play05:09

поступили умнее и сделали атлас в

play05:11

котором почти все элементы расположены

play05:13

по сетке и в данном примере размера

play05:15

ячейки равен 16 16 пикселей поэтому мы

play05:17

можем нажать на меню слайс выбрать тип

play05:20

нарезки цел bike ride says указать

play05:22

размеры тейкер 16 на 16 пикселей и жать

play05:24

слайд после этого unity сам она режет

play05:26

атлас на спрайт и размеров 16 на 16

play05:29

пикселей

play05:29

нам остается только удалить ненужные

play05:31

ячейки в которых находятся месяце и

play05:33

поместить его в одну большую ячейку

play05:35

после этого можно нажимать тёплой в

play05:37

правом верхнем углу и все наша атлас

play05:39

нарезал и готов к использованию

play05:42

в заключение хочу дать несколько советов

play05:45

о том как использовать атласа спрайтов и

play05:47

какие спрайты в них паковать лично я

play05:49

пакую в атлас и все что только можно и в

play05:52

особенности то что часто используется в

play05:54

игре в пределах одного экрана например у

play05:56

меня может быть атласов телефонами для

play05:57

кнопок атлас со всеми иконками атлас со

play06:00

всеми элементами игровые локации атлас

play06:02

каким-то одним персонажем и всеми его

play06:04

анимациями то мы и так далее для того

play06:06

чтобы понять какие спрайты твои игры

play06:08

нужно паковать в атлас и и какать атласа

play06:10

разделять просто посмотрели свою игру по

play06:12

экрана выделить те картинки которая

play06:14

часто используются вместе и при этом в

play06:16

пределах одного экрана это могут быть

play06:18

разные слои игрового уровня например

play06:20

атлас блоками атлас с элементами

play06:22

окружения атлас анимации персонажей

play06:24

атлас врагами отл с бонусами там мы и

play06:27

так далее это все зависит от количества

play06:29

спрайтов твоей игре но в идеале все

play06:31

должно умещаться на 1 отл с размером до

play06:33

2048 на 2048 пикселей в идеале

play06:36

группировать атласы нужно таким образом

play06:38

чтобы на сцене время рендера

play06:40

использовались все спрайты из атласа так

play06:43

как если хотя бы один спрайт и запроса

play06:44

используется на сцене то устройство в

play06:46

памяти держит весь атлас целиком а

play06:48

размер до 2048 на 2048 пикселей

play06:51

обуславливаются тем что на больший атлас

play06:54

будет уходить больше времени на выборку

play06:56

и соответственно больше нагрузка на

play06:57

устройство исходя из всего

play06:59

вышесказанного можно выделить два

play07:00

основных правила по группировке спрайтов

play07:02

атласа

play07:03

первое это пакуем все что используется в

play07:05

пределах одного экрана и второе это

play07:07

стараемся сделать

play07:09

атлас максимально маленького размера так

play07:11

как меньше размер атласа меньше нагрузка

play07:13

на выборку но тут есть момент с

play07:14

противоположной стороны если мы сделаем

play07:17

атлас слишком маленького размера то вся

play07:19

графика нашей игры будет больше похожа

play07:20

на мыло поэтому тут нужно искать баланс

play07:22

между качеством графики и размерам

play07:24

атласа

play07:25

на этом у меня все если это видео тебе

play07:26

помогло то ты в идеале можно зайти на

play07:29

данный шин аллерс и поддержать меня

play07:31

всемогущим доллар доллар в наше время

play07:33

решает много но и независимо от его

play07:35

решение спасибо за просмотр и это мэтт

play07:37

кнопочка лайк а есть на нее бы тоже

play07:39

желательно тыкнуть и если ты еще не

play07:41

подписан то подписаться

play07:44

[музыка]

Rate This

5.0 / 5 (0 votes)

Étiquettes Connexes
Unity OptimizationSprite AtlasGame DevelopmentGraphics APIRendering Efficiency2D GameAsset PackingPerformance TipsVideo TutorialUnity Engine
Besoin d'un résumé en anglais ?