Примеры использования CanvasGroup в Unity.

Сегодня я хочу рассказать об одной компоненте из библиотеки uGUI, незнание которой породило мной ряд “костылей” в нескольких проектах, что привело к большему количеству кода, работы, и как следствие, ошибок.

Компонента – CanvasGroup.

Если знать про её существование заранее, то исчерпывающую информацию можно получить из документации и спокойно применять полученные знания.

Я же коснусь всех настроек “CanvasGroup” чуть подробнее и с примерами, дабы в памяти остался визуальный слепок и легко извлекся в последствии, когда понадобится.

Основное предназначение “CanvasGroup” – это управление группой UI-элементов, которые находятся ниже по иерархии (“внутри” CanvasGroup). Так же, эти настройки распространяются на сам “GameObject”, содержащий компоненту “CanvasGroup”.
Например, мы хотим управлять сразу всеми элементами в окне, группой кнопок или группой картинок.

Настройки “CanvasGroup”

Как видно из картинки выше, “CanvasGroup” содержит всего четыре настройки, о назначении которых можно легко догадаться из названий. Однако, пройдемся подробнее:

1. Alpha.

Управление прозрачностью группы UI-элементов. Изменяет прозрачность как корневого UI-элемента, на котором находится компонента CanvasGroup, так и всех дочерних UI-элементов.

Один из сценариев использования – сделать группу объектов полупрозрачными, не изменяя цвет каждого объекта:

Меняем прозрачность группы UI-элементов


Другой часто встречающийся сценарий – эффект исчезновения (FadeOut) и эффект появления (FadeIn) окна. Для реализации такого эффекта, без использования CanvasGroup, нам бы пришлось получать все UI-элементы, которые расположены на окне, и изменять параметр alpha у цвета для каждого найденного элемента (например, с помощью метода CrossFadeAlpha). Но и этого было бы не достаточно, так как некоторые UI-элементы на окне могут быть в полупрозрачном состоянии, и после того, как мы применили эффект исчезновения, путем изменения alpha до нуля, нам бы пришлось по завершению восстанавливать изначальный параметр alpha. Таким образом, необходимо было бы сохранять все параметры alpha для каждого UI-элемента, потом применять эффект и по завершению восстанавливать все параметры alpha для каждого UI-элемента. Много ненужной работы.

CanvasGroup упрощает процесс создания таких эффектов.

Эффекты Fade Out и Fade In

Для себя я написал два твина, которые реализуют эффекты исчезновения (FadeOutTween) и появления (FadeInTween) с помощью CanvasGroup и которые можно использовать “в одну строчку”:

public void OnGUI()
{
    if (GUILayout.Button("Fade Out/In"))
    {
         TweenSequence.Run(
            () => FadeOutTween.Run(Panel, Duration),
            () => FadeInTween.Run(Panel, Duration).SetDelay(0.25f));
    }
}

2. Interactable.

Позволяет сделать группу UI-элементов недоступными для взаимодействия (эквивалент enable/disable из множества других UI-фреймворков). Например, сделать невосприимчивыми к клику набор кнопок или все элементы на окне.

Делаем недоступной для ввода группу кнопок

3. Blocks Raycasts.

Блокирует все пользовательские действия над UI-элементами, которые реализованы через “Raycasts”. К примеру, отображаем поверх одного окна другое, и если вышележащее окно по размеру не перекрывает нижележащее, то возможность взаимодействовать с UI-элементами нижележащего окна останется. И для блокировки этой возможности мы можем использовать параметр “BlocksRaycast” на нижележащем окне.

Блокируем возможность взаимодействовать с UI-элементами нижележащего окна

Отличие от параметра “Interactable” в том, что “Interactable” переводит все UI-элементы в состояние “disabled”, и если UI-элемент имеет отдельный внешний вид для состояния “disabled”, то он меняет свой внешний вид на “disabled”. “BlockRaycasts” же просто блокирует весь пользовательский ввод без изменения внешнего вида.

4. Ignore Parent Groups.

Игнорируем все настройки CanvaGroup, которые находятся вверх по иерархии UI-элементов (своеобразная перегрузка-сброс всех настроек CanvasGroup).

Одна из кнопок использует настройки Ingore Parent Group

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

Все примеры можно взять на github.

5 3 votes
Article Rating
Subscribe
Notify of
guest
308 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback
3 years ago

nytimes

[…]Sites of interest we have a link to[…]

trackback
3 years ago

norwaytoday

[…]check below, are some absolutely unrelated websites to ours, on the other hand, they are most trustworthy sources that we use[…]

trackback
3 years ago

dutchnews

[…]the time to study or visit the subject material or sites we have linked to below the[…]

trackback
3 years ago

cphpost

[…]Every when in a while we opt for blogs that we read. Listed beneath would be the latest web sites that we opt for […]

trackback
3 years ago

aftonbladet

[…]usually posts some really interesting stuff like this. If you’re new to this site[…]

trackback
3 years ago

spiegel

[…]The info talked about inside the write-up are a number of the very best readily available […]

trackback
3 years ago

postimees

[…]although web sites we backlink to below are considerably not connected to ours, we feel they’re in fact worth a go as a result of, so have a look[…]

trackback
3 years ago

lemonde

[…]here are some hyperlinks to web sites that we link to because we feel they are worth visiting[…]

trackback
3 years ago

helsinkitimes

[…]please take a look at the web pages we stick to, like this a single, as it represents our picks from the web[…]

trackback
3 years ago

icelandreview

[…]Wonderful story, reckoned we could combine some unrelated information, nonetheless truly really worth taking a search, whoa did one study about Mid East has got much more problerms as well […]

trackback
3 years ago

thesouthafrican

[…]usually posts some very intriguing stuff like this. If you’re new to this site[…]

trackback
3 years ago

우리카지노

[…]below you will come across the link to some websites that we believe you must visit[…]

trackback
3 years ago

mature porn

[…]we prefer to honor quite a few other world wide web web pages on the net, even though they aren’t linked to us, by linking to them. Below are some webpages worth checking out[…]

trackback
3 years ago

퍼스트카지노

[…]always a massive fan of linking to bloggers that I enjoy but really don’t get lots of link love from[…]

trackback

مباريات اليوم بث مباشر

[…]Sites of interest we have a link to[…]

trackback
3 years ago

mahrajanat

[…]usually posts some pretty intriguing stuff like this. If you’re new to this site[…]

trackback
3 years ago

best g spot vibrator

[…]here are some hyperlinks to internet sites that we link to for the reason that we feel they may be really worth visiting[…]

trackback
3 years ago

Japanese Porn Land

[…]very few web-sites that transpire to become comprehensive beneath, from our point of view are undoubtedly nicely worth checking out[…]

trackback
3 years ago

TransHub

[…]usually posts some really exciting stuff like this. If you’re new to this site[…]

trackback
3 years ago

xnxn

[…]check beneath, are some entirely unrelated internet websites to ours, having said that, they are most trustworthy sources that we use[…]

trackback
3 years ago

langley plumber

[…]that will be the end of this report. Here you’ll come across some websites that we consider you will enjoy, just click the hyperlinks over[…]

trackback
3 years ago

Gay Hub XXX

[…]although websites we backlink to below are considerably not connected to ours, we really feel they may be basically worth a go by means of, so possess a look[…]

trackback

Cavachon puppies for sale

[…]just beneath, are a lot of entirely not related web-sites to ours, even so, they’re certainly really worth going over[…]

trackback

Belgian malinois puppies for sale

[…]we came across a cool web-site which you may possibly take pleasure in. Take a appear should you want[…]

trackback

where to buy medical marijuana online

[…]check below, are some entirely unrelated sites to ours, nonetheless, they’re most trustworthy sources that we use[…]

trackback
3 years ago

Mining

[…]Here are a few of the web pages we advise for our visitors[…]

trackback
3 years ago

Mining

[…]Wonderful story, reckoned we could combine a number of unrelated information, nevertheless definitely really worth taking a search, whoa did one particular master about Mid East has got additional problerms as well […]

trackback
3 years ago

Twink Gay Porn

[…]very couple of websites that transpire to be in depth beneath, from our point of view are undoubtedly nicely worth checking out[…]

trackback
3 years ago

MILF Porn

[…]Sites of interest we’ve a link to[…]

trackback

Digital Marketing Services

[…]check below, are some absolutely unrelated web-sites to ours, nevertheless, they may be most trustworthy sources that we use[…]

trackback

Mountain bike clothing

[…]below you will uncover the link to some web sites that we believe you ought to visit[…]

trackback
3 years ago

best kratom vendors

[…]The info mentioned inside the post are some of the very best offered […]

trackback
285
3 years ago

285

[…]just beneath, are many completely not related internet sites to ours, however, they are surely really worth going over[…]

trackback
3 years ago

best broker for loan

[…]that would be the end of this article. Right here you will find some websites that we think you will enjoy, just click the links over[…]

trackback

https://dankvapescartriges.com/product/la-confidential/

[…]The info talked about inside the write-up are a few of the ideal readily available […]

trackback
3 years ago

샌즈카지노

[…]one of our guests not long ago suggested the following website[…]

trackback
3 years ago

우리카지노

[…]usually posts some quite exciting stuff like this. If you are new to this site[…]

trackback
3 years ago

메리트카지노

[…]always a major fan of linking to bloggers that I really like but do not get a whole lot of link appreciate from[…]

trackback
3 years ago

퍼스트카지노

[…]The data talked about inside the write-up are several of the very best accessible […]

trackback
3 years ago

코인카지노

[…]always a huge fan of linking to bloggers that I adore but don’t get a great deal of link adore from[…]

trackback
3 years ago

Buy Weed Online

[…]please check out the web sites we adhere to, including this 1, as it represents our picks in the web[…]

trackback
3 years ago

AnaGlobal

[…]the time to read or check out the content material or web pages we’ve linked to below the[…]

trackback
3 years ago

click here

[…]although web-sites we backlink to below are considerably not associated to ours, we really feel they are essentially really worth a go via, so possess a look[…]

trackback
3 years ago

best cbd oil

[…]although internet sites we backlink to below are considerably not related to ours, we really feel they’re really worth a go via, so possess a look[…]

trackback
3 years ago

cargo ship cruise

[…]Here is a superb Weblog You may Find Fascinating that we Encourage You[…]

trackback
3 years ago

cbd for depression

[…]please visit the web sites we adhere to, like this one particular, as it represents our picks from the web[…]

trackback
3 years ago

cbd for sale

[…]The data mentioned in the post are several of the best obtainable […]

trackback
3 years ago

cbd for dogs

[…]here are some hyperlinks to web-sites that we link to due to the fact we feel they’re worth visiting[…]

trackback
3 years ago

best cbd gummies

[…]check beneath, are some totally unrelated sites to ours, having said that, they may be most trustworthy sources that we use[…]

trackback
3 years ago

best cbd for dogs

[…]very few internet sites that occur to be detailed beneath, from our point of view are undoubtedly well worth checking out[…]

308
0
Would love your thoughts, please comment.x
()
x