(十二)交互组件Selectable

文章目录

1.前言

简单说一下unity的交互组件Selectable,此组件是所有组件交互的基类,即它实现了鼠标hover、点击、离开以及其他事件对应的状态。是button、toggle、slider等的基类,比较简单。

2.实现

其实现比较简单,即简单继承一些事件接口(如IPointerDownHandler),然后获取事件,根据事件去处理不同的逻辑。而此组件看起来比较复杂(1000+行的代码),是为了处理一些特殊情况,比较复杂的功能是如下两个:
1、Transition的选择,即根据其不同值选择不同的表现形式。
2、接收父CanvasGroup的管控。此功能通过继承UIBehavior获取监听,然后做逻辑处理,比如CanvasGroup更换了如何处理:

        protected override void OnCanvasGroupChanged()
        {
    
    
            // Figure out if parent groups allow interaction
            // If no interaction is alowed... then we need
            // to not do that :)
            var groupAllowInteraction = true;
            Transform t = transform;
            while (t != null)
            {
    
    
                t.GetComponents(m_CanvasGroupCache);
                bool shouldBreak = false;
                for (var i = 0; i < m_CanvasGroupCache.Count; i++)
                {
    
    
                    // if the parent group does not allow interaction
                    // we need to break
                    if (!m_CanvasGroupCache[i].interactable)
                    {
    
    
                        groupAllowInteraction = false;
                        shouldBreak = true;
                    }
                    // if this is a 'fresh' group, then break
                    // as we should not consider parents
                    if (m_CanvasGroupCache[i].ignoreParentGroups)
                        shouldBreak = true;
                }
                if (shouldBreak)
                    break;

                t = t.parent;
            }

            if (groupAllowInteraction != m_GroupsAllowInteraction)
            {
    
    
                m_GroupsAllowInteraction = groupAllowInteraction;
                OnSetProperty();
            }
        }

3.最后

此类比较简单,如果我们自己定义组件时可以简单继承相关接口实现自己的逻辑,unity的selectable也是为了实现“unity式”的ui而定义。

猜你喜欢

转载自blog.csdn.net/qq_37833413/article/details/124928952
今日推荐