Примеры использования 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.

97
Leave a Reply

avatar
97 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
скачать гдз виленкин классхарактеристика краткосрочных обязательств организацииthe little mermaid 2 return to the sea melody meets tip and dashgrand theft auto san andreas ios cheats cydiaгост 1105 84 Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
литература 7 класс г.с.меркин ответы на вопросы часть
Guest

Hello, i feel that i noticed you visited my site so i got here to return the want?.I am trying to to find issues to enhance my website!I suppose its ok to use a few of your ideas!!| а

гост накидные гайки
Guest

I think this is among the most significant info for me. And i’m glad reading your article. But want to remark on some general things, The website style is wonderful, the articles is really excellent : D. Good job, cheers| а

unreal tournament iii serial key
Guest

Informative article, exactly what I wanted to find.| а

windows 7 ultimate oem slp product key
Guest

This excellent website certainly has all of the information and facts I needed about this subject and didn’t know who to ask. | а

приказ о персональных данных в школе
Guest

Appreciating the time and effort you put into your website and in depth information you present. It’s nice to come across a blog every once in a while that isn’t the same old rehashed information. Great read! I’ve saved your site and I’m adding your RSS feeds to my Google account.| а

трудовой договор с единственным учредителем генеральным директором ооо образец
Guest

Hi there, for all time i used to check webpage posts here in the early hours in the break of day, as i enjoy to gain knowledge of more and more.| а

отдельная спецификация является отдельным договором
Guest

Hey would you mind stating which blog platform you’re working with? I’m looking to start my own blog soon but I’m having a difficult time making a decision between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something unique. P.S Apologies for being off-topic but I had to ask!| а

black label society full album youtube
Guest

Excellent post. I was checking continuously this blog and I am impressed! Extremely helpful information particularly the last part 🙂 I care for such info a lot. I was seeking this particular info for a very long time. Thank you and good luck.| а

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

Hello there! This post couldn’t be written much better! Looking at this article reminds me of my previous roommate! He continually kept talking about this. I’ll forward this article to him. Fairly certain he’s going to have a very good read. Thanks for sharing!| а

радиоуправление игрушек схема
Guest

Howdy! Would you mind if I share your blog with my myspace group? There’s a lot of people that I think would really appreciate your content. Please let me know. Cheers| а

характеристика на врача анестезиолога реаниматолога
Guest

Hello, Neat post. There is a problem with your website in web explorer, would check this? IE still is the market leader and a big component to folks will pass over your magnificent writing due to this problem.| а

bad dogz windows xp sp3 vista vistavge
Guest

It’s amazing to go to see this website and reading the views of all colleagues regarding this post, while I am also zealous of getting knowledge.| а

сборник задач по общей биологии 11 класс дубков богачева
Guest

This post provides clear idea for the new visitors of blogging, that truly how to do running a blog.| а

бланк командировки
Guest

Thanks for sharing your thoughts on %meta_keyword%. Regards| а

businesscards mx v3.98 mlb
Guest

Thanks for sharing your thoughts on %meta_keyword%. Regards| а

tuneup utilities 2019 ger keygen free download crack patch
Guest

I like the valuable info you supply for your articles. I will bookmark your weblog and check again right here regularly. I am rather sure I will be told many new stuff proper here! Best of luck for the next!| а

сочинение-сказка 5 класс
Guest

Greetings from California! I’m bored at work so I decided to check out your website on my iphone during lunch break. I love the info you present here and can’t wait to take a look when I get home. I’m shocked at how quick your blog loaded on my mobile .. I’m not even using WIFI, just 3G .. Anyhow, great blog!| а

adobe reader latest version for windows 7 filehippo
Guest

What’s up to all, it’s actually a good for me to pay a quick visit this web site, it contains valuable Information.| а

гдз по истории 8 класс ведюшкин без скачивания
Guest

Pretty nice post. I just stumbled upon your blog and wanted to say that I’ve truly enjoyed browsing your blog posts. In any case I will be subscribing to your rss feed and I hope you write again soon!| а

гдз по биологии-суматохин. кучменко
Guest

Interesting blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog jump out. Please let me know where you got your theme. Appreciate it| а

бланк официальный протокол хоккейного матча
Guest

Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.| а

самолетики в бухгалтерском учете бланк скачать
Guest

Amazing blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple tweeks would really make my blog shine. Please let me know where you got your design. Thank you| а

как научить ребёнка решать задачи в 5 классе
Guest

Hello there! Do you know if they make any plugins to assist with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success. If you know of any please share. Thank you!| а

рецепт борща с сельдереем
Guest

My brother suggested I might like this blog. He used to be totally right. This post truly made my day. You can not consider just how much time I had spent for this information! Thank you!| а

история средних веков крючкова все д з
Guest

Hi, I do think your blog might be having web browser compatibility issues. When I take a look at your web site in Safari, it looks fine however when opening in IE, it’s got some overlapping issues. I merely wanted to give you a quick heads up! Other than that, fantastic website!| а

решебник по немецкому языку 10 класс бим садомова лытаева смотреть
Guest

I have read so many articles regarding the blogger lovers but this post is actually a nice piece of writing, keep it up.| а

структурная схема микропроцессора кр580вм80а
Guest

I will immediately take hold of your rss as I can’t find your e-mail subscription link or e-newsletter service. Do you have any? Please let me recognize in order that I may subscribe. Thanks.| а

warcraft 3 frozen throne free download full version 1.26
Guest

Hello, I read your blogs like every week. Your writing style is awesome, keep up the good work!| а

oo defrag 17 pro keygen
Guest

I think this is one of the most important information for me. And i’m glad reading your article. But want to remark on few general things, The website style is great, the articles is really great : D. Good job, cheers| а

acer aspire 5920 lan drivers download
Guest

I am really loving the theme/design of your weblog. Do you ever run into any browser compatibility problems? A handful of my blog audience have complained about my website not working correctly in Explorer but looks great in Firefox. Do you have any ideas to help fix this problem?| а

техническая характеристика кондиционеры сплит системы
Guest

I’m gone to inform my little brother, that he should also pay a visit this blog on regular basis to get updated from most recent news.| а

texet tm 9741 характеристики
Guest

I am sure this paragraph has touched all the internet people, its really really nice piece of writing on building up new webpage.| а

схемa ресурсов мирового океaнa
Guest

I have been browsing online more than 2 hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my view, if all website owners and bloggers made good content as you did, the internet will be a lot more useful than ever before.| а

tuneup utilities 2020 spanish full mega portable
Guest

There is definately a lot to learn about this subject. I love all the points you made.| а

trackback

https://royalcbd.com/product/cbd-oil-250mg/

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

trackback

https://royalcbd.com/product/cbd-gummies-25mg/

[…]below you will obtain the link to some sites that we feel you need to visit[…]

гост 24297 78
Guest

Today, I went to the beach front with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!| а

trackback

https://royalcbd.com/product/cbd-roll-on-gel/

[…]below you’ll come across the link to some internet sites that we think you should visit[…]

trackback

https://royalcbd.com/shop/

[…]here are some links to web pages that we link to simply because we feel they’re really worth visiting[…]

trackback

https://royalcbd.com/blog/

[…]The details mentioned inside the report are some of the very best offered […]

mapinstall v3 14 2 special edition
Guest

You could certainly see your expertise in the article you write. The sector hopes for even more passionate writers like you who aren’t afraid to mention how they believe. All the time follow your heart.| а

trackback

Earn money online

[…]we came across a cool site that you might appreciate. Take a look in case you want[…]

blackberry desktop manager 5 download free
Guest

Hello There. I found your blog the usage of msn. That is an extremely smartly written article. I’ll make sure to bookmark it and return to read more of your helpful info. Thank you for the post. I will certainly comeback.| а

trackback

Coinpunk

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

бланк для налогового вычета 3 ндфл
Guest

Oh my goodness! Amazing article dude! Many thanks, However I am encountering difficulties with your RSS. I don’t know why I cannot subscribe to it. Is there anybody having the same RSS issues? Anybody who knows the answer can you kindly respond? Thanx!!| а

trackback

Love Vibe: Aria

[…]Wonderful story, reckoned we could combine a couple of unrelated data, nevertheless truly really worth taking a look, whoa did one particular master about Mid East has got far more problerms also […]

test drive unlimited 2 online status ps3
Guest

Hey! I know this is kinda off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one? Thanks a lot!| а

sacred2 patch v.2.12crack by irbisweb
Guest

No matter if some one searches for his essential thing, thus he/she desires to be available that in detail, thus that thing is maintained over here.| а

trackback

Business Apps

[…]Here is a superb Weblog You might Come across Fascinating that we Encourage You[…]

trackback

کلیپ سکسی

[…]very couple of web-sites that occur to be comprehensive beneath, from our point of view are undoubtedly nicely worth checking out[…]