(十二)互動元件Selectable
阿新 • • 發佈:2022-05-23
文章目錄
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而定義。