直接继承自UIBehaviour
public void RegisterToggle(Toggle toggle)
{
if (!m_Toggles.Contains(toggle))
m_Toggles.Add(toggle);
if (!allowSwitchOff && !AnyTogglesOn())
{
toggle.isOn = true;
NotifyToggleOn(toggle);
}
}
public void UnregisterToggle(Toggle toggle)
{
if (m_Toggles.Contains(toggle))
m_Toggles.Remove(toggle);
if (!allowSwitchOff && !AnyTogglesOn() && m_Toggles.Count != 0)
{
m_Toggles[0].isOn = true;
NotifyToggleOn(m_Toggles[0]);
}
}
/// <summary>
/// Notify the group that the given toggle is enabled.
/// </summary>
/// <param name="toggle">The toggle that got triggered on</param>
public void NotifyToggleOn(Toggle toggle, bool sendCallback = true)
{
ValidateToggleIsInGroup(toggle);
// disable all toggles in the group
for (var i = 0; i < m_Toggles.Count; i++)
{
if (m_Toggles[i] == toggle)
continue;
if (sendCallback)
m_Toggles[i].isOn = false;
else
m_Toggles[i].SetIsOnWithoutNotify(false);
}
}
public ToggleEvent onValueChanged = new ToggleEvent();
接口触发回调。void Set(bool value, bool sendCallback = true)
{
if (m_IsOn == value)
return;
// if we are in a group and set to true, do group logic
m_IsOn = value;
if (m_Group != null && IsActive())
{
if (m_IsOn || (!m_Group.AnyTogglesOn() && !m_Group.allowSwitchOff))
{
m_IsOn = true;
m_Group.NotifyToggleOn(this, sendCallback);
}
}
// Always send event when toggle is clicked, even if value didn't change
// due to already active toggle in a toggle group being clicked.
// Controls like Dropdown rely on this.
// It's up to the user to ignore a selection being set to the same value it already was, if desired.
PlayEffect(toggleTransition == ToggleTransition.None);
if (sendCallback)
{
UISystemProfilerApi.AddMarker("Toggle.value", this);
onValueChanged.Invoke(m_IsOn);
}
}
List<Toggle> m_Toggles
申明为List,变长数组(类似C++的vector),而注册/反注册接口使用了Contain、Remove,除此之外还有些查找操作,更适合使用map/hashmap/set。C# List 源码Contains:
// Contains returns true if the specified element is in the List.
// It does a linear, O(n) search. Equality is determined by calling
// item.Equals().
//
public bool Contains(T item) {
if ((Object) item == null) {
for(int i=0; i<_size; i++)
if ((Object) _items[i] == null)
return true;
return false;
}
else {
EqualityComparer<T> c = EqualityComparer<T>.Default;
for(int i=0; i<_size; i++) {
if (c.Equals(_items[i], item)) return true;
}
return false;
}
}
Remove: 这个用在这里更废,先遍历找到item对应下标,再从数组中移除(需要将index后的元素复制到前面)
// Removes the element at the given index. The size of the list is
// decreased by one.
//
public bool Remove(T item) {
int index = IndexOf(item);
if (index >= 0) {
RemoveAt(index);
return true;
}
return false;
}