[UNITY] Атласы спрайтов
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
😀 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.
🛠️ 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
💡Sprites
💡Optimization
💡Draw Call
💡Unity
💡Packing
💡Frame Debugger
💡Pivot
💡Texture
💡2D Sprite Editor
💡Grid
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
всем привет и хочу сразу извиниться за
свое довольно долго отсутствие
это связано с тем что мне нужно было
переводиться из одного колледжа в другой
и попутно собирать кучу документов для
военкомата а живу я довольно далеко от
города и поэтому времени на видео у меня
почти не оставалось но сейчас все в
норме и я могу продолжать делать для вас
новые видео сегодня хочу рассказать про
атлас и спрайтов это большие картинки
внутри которых множество других картинок
и используются они как правило для
оптимизации игры и в частности для того
чтобы уменьшить количество вызовов
метода отрисовки для рендера каждого
кадра каждый кадр любой 2d игры состоит
из картинок и если все они хранятся в
виде отдельных картинок то на прорисовку
каждой такой картинки unity будет
тратить один вызов метода дроу
графического api
большое количество вызовов метода дроу
будет гарантировать вам большую нагрузку
на железо и соответственно низкий fps
но если объединить все картинки в отл
астана рендер каждого атласа будет
уходить только один для укол чтобы было
понятней я открою сцену в unity и включу
фрейм дебаг тут можно увидеть процесс
рендера каждого кадра в данном случае
чтобы от рендерить один кадр этой
статичные менюшки и unity нужно 25 раз
обращаться к графическому опять это
довольно много учитывая то что это
менюшка она просто набор картинок то
есть некие их анимации эффектов скриптов
и какой-либо логики да и в конце концов
если мы можем сделать игру более
производительные просто упаковав часто
использующиеся вместе картинки в атлас и
то почему бы и нет
создать атлас поэтов можно несколькими
способами и самый простой из них это
встроенный механизм unity по упаковке
spite of либо можно самому сделать
большую картинку в фотошопе или
иллюстраторе и нарезать ее на отдельные
спрайты уже внутри юлить и в этом видео
мы рассмотрим оба способа и начнём с
самого простого вначале нам нужно
включить про питер для этого открываем
project settings
переходим во вкладку эти дары и в
разделе спрайт покер переключаем
качельку либо на элвиса на и болт либо
на иное будку bells после этого
переходим в папку с проектом и клацаем
тут правой царской кнопкой мыши и
создаем спрайт атлас для примера я
назову его юань далее нажимаем на
замочек в инспекторе чтобы заблокировать
это окно другими словами когда мы будем
выбирать картинки у нас не будет
открываться их инспектор пока мы не
снимем этот замочек далее я отключу и
лаура тишин этой tracking отключение и
лаура тиша не даст unity поворачивать
спрайты внутри атласа а права-то и
speaking ты можешь почитать по ссылке в
описании там вроде чё то чтобы контуры
одного объекта они перекрывали контур
другого объекта типа если это и tracking
включён то юлить и более плотно
размещает объекты внутри атласа но это
чревато тем что контур одного объекта
могут пересекать контуры другого тут
сейчас будут два скриншота со включенным
и отключенном то и трекингом вот типа в
чем разница теперь мы можем выделить все
спрайты которые мы хотим упаковать и
перетащить их на надпись яндекс
hobbyking и они автоматически добавится
в облас теперь нажимаем на кнопку п
превью и все атлас готов я хаза почему
но в инспекторе ваншота криво
отображается то есть у текстурки
поехавшие
и вообще нет этих отступов это вот
именно в инспекторе но в игре всё норм
теперь можно снова посмотреть во фрейм
дебаггер и тут такой момент то которым я
затупил так как ничего не изменилось и у
нас утешит 24 бача да и отрисовка
каждого кадра проходят абсолютно так же
как и до создания атласа спрайтов я
погубил где-то минут 10 типа как этой
штукой пользоваться потому что до этого
я использовал внешне от вас и спрайтов о
них дальше видео и по факту нужно было
всего лишь нажать на кнопку play и вуаля
25 бача изменились на 8 что в три раза
меньше и если посмотреть во френд бак то
можно увидеть что все кнопки с иконками
рендерится за 12 кал в описании к этому
видео будет ссылка на
а документацию по встроенному в unity
упаковщику спрайтов там можно прочитать
какая галочка и за что отвечает да и там
вообще много всего полезного написано на
дальше мы переходим к более привычным
они атласа спрайтов это именно внешний
атласа то есть потому что я предпочитаю
паковать картиночки вручную в
какой-нибудь фотошопе или иллюстраторе а
в юрий импортировать уже готовы большую
картинку и вот как раз таки о том как
эту картинку импортировать и как
нарезать ее на отдельные спрайты я и
расскажу как я говорил ранее атласа
spite of можно создавать и за пределами
unity
из-за того что атласа спрайтов это
просто большие картинки для которых
множество других картинок не могут
создаваться в любых графических
редакторах фигу мой иллюстратор
photoshop и многие другие от себя могу
посоветовать создавать атласов по сеткам
для того чтобы при импорте ты знал на
сто процентов размер каждой картинки
ну или если ты про то ты можешь паковать
картинки как можно плотнее чтобы размер
атласа получился меньше для того чтобы
нарезать атласу на спрайт и нам нужен
пакет 2d спрайт если он у тебя не
установлен то зайди в птс менеджер вбей
в поиск суда спрайты ты пнин стол после
этого ты уже можешь переходить к нарезке
атласа чтобы редактор понял что эта
картинка представляет из себя атлас
нужно в инспекторе а поменять ее спрайт
mods a single на multiple и ножа тёплой
после этого жмем на кнопку с пройдите у
нас откроется окно редактора спрайта в
котором нам нужно разделить большой
атлас на множество маленьких картинок
это можно сделать руками просто помещая
в рамку каждый из элементов на мы
поступили умнее и сделали атлас в
котором почти все элементы расположены
по сетке и в данном примере размера
ячейки равен 16 16 пикселей поэтому мы
можем нажать на меню слайс выбрать тип
нарезки цел bike ride says указать
размеры тейкер 16 на 16 пикселей и жать
слайд после этого unity сам она режет
атлас на спрайт и размеров 16 на 16
пикселей
нам остается только удалить ненужные
ячейки в которых находятся месяце и
поместить его в одну большую ячейку
после этого можно нажимать тёплой в
правом верхнем углу и все наша атлас
нарезал и готов к использованию
в заключение хочу дать несколько советов
о том как использовать атласа спрайтов и
какие спрайты в них паковать лично я
пакую в атлас и все что только можно и в
особенности то что часто используется в
игре в пределах одного экрана например у
меня может быть атласов телефонами для
кнопок атлас со всеми иконками атлас со
всеми элементами игровые локации атлас
каким-то одним персонажем и всеми его
анимациями то мы и так далее для того
чтобы понять какие спрайты твои игры
нужно паковать в атлас и и какать атласа
разделять просто посмотрели свою игру по
экрана выделить те картинки которая
часто используются вместе и при этом в
пределах одного экрана это могут быть
разные слои игрового уровня например
атлас блоками атлас с элементами
окружения атлас анимации персонажей
атлас врагами отл с бонусами там мы и
так далее это все зависит от количества
спрайтов твоей игре но в идеале все
должно умещаться на 1 отл с размером до
2048 на 2048 пикселей в идеале
группировать атласы нужно таким образом
чтобы на сцене время рендера
использовались все спрайты из атласа так
как если хотя бы один спрайт и запроса
используется на сцене то устройство в
памяти держит весь атлас целиком а
размер до 2048 на 2048 пикселей
обуславливаются тем что на больший атлас
будет уходить больше времени на выборку
и соответственно больше нагрузка на
устройство исходя из всего
вышесказанного можно выделить два
основных правила по группировке спрайтов
атласа
первое это пакуем все что используется в
пределах одного экрана и второе это
стараемся сделать
атлас максимально маленького размера так
как меньше размер атласа меньше нагрузка
на выборку но тут есть момент с
противоположной стороны если мы сделаем
атлас слишком маленького размера то вся
графика нашей игры будет больше похожа
на мыло поэтому тут нужно искать баланс
между качеством графики и размерам
атласа
на этом у меня все если это видео тебе
помогло то ты в идеале можно зайти на
данный шин аллерс и поддержать меня
всемогущим доллар доллар в наше время
решает много но и независимо от его
решение спасибо за просмотр и это мэтт
кнопочка лайк а есть на нее бы тоже
желательно тыкнуть и если ты еще не
подписан то подписаться
[музыка]
Посмотреть больше похожих видео
Pygame Movement - Pygame RPG Tutorial #2
How To Make a Topdown RPG in Godot 4: Adding The Player (Part 1)
Cara Membuat Tetris sederhana untuk pemula di Mit App inventor GRATIS 2024 | programmer pemula
UV Maps Explained
How To Make A Game with GDevelop - Menus and Publishing (E11)
This seller tool told me what amazon sellers NEED!【Brief information about sellersprite】
5.0 / 5 (0 votes)