不带动画
带动画
实现代码
public class Nodes : BaseNode
{
private static Text text
;
public override void Start()
{
text
= GameObject
.Find("Canvas/CurrentClickNodeText").GetComponent<Text>();
base.Start();
GetComponent<Button>().onClick
.AddListener(() =>
{
SwitchNode();
Text txt
= transform
.GetChild(0).GetComponent<Text>();
text
.text
= txt
.text
;
});
}
}
public abstract class BaseNode : MonoBehaviour
{
public RectTransform parentRectTransform
;
public List
<BaseNode
> childNodes
;
public static BaseNode CurrentNode
{ get; private set; }
private bool isOpen
= false;
private float EndContainerWidth
;
private float StartContainerWidth
;
[Range(0.0f, 1f)] private float EleasticSpeed
= 0.5f;
public virtual void Start()
{
if (parentRectTransform
!= null)
{
StartContainerWidth
= parentRectTransform
.rect
.width
;
if (this.childNodes
!= null && this.childNodes
.Count
!= 0)
{
float space
= parentRectTransform
.GetComponent<HorizontalLayoutGroup>().spacing
;
for (int i
= 0; i
< this.childNodes
.Count
; i
++)
{
EndContainerWidth
+= childNodes
[i
].GetComponent<RectTransform>().rect
.width
+ space
;
}
EndContainerWidth
+= this.parentRectTransform
.rect
.width
;
}
}
}
public void SwitchNode()
{
if (CurrentNode
!= null && CurrentNode
.childNodes
.Count
!= 0)
{
if (CurrentNode
== this && CurrentNode
.childNodes
!= null)
{
this.isOpen
= !isOpen
;
StartCoroutine(CotainerSiwtch(isOpen
, CurrentNode
));
foreach (var node
in CurrentNode
.childNodes
)
{
node
.isOpen
= false;
}
CurrentNode
= null;
return;
}
else
{
if (this.childNodes
.Count
== 0) return;
StartCoroutine(CotainerSiwtch(false, CurrentNode
));
foreach (var node
in CurrentNode
.childNodes
)
{
node
.isOpen
= false;
}
CurrentNode
.isOpen
= false;
CurrentNode
= null;
}
}
if (this.childNodes
!= null && this.childNodes
.Count
!= 0)
{
this.isOpen
= !isOpen
;
StartCoroutine(CotainerSiwtch(this.isOpen
, this));
foreach (var node
in this.childNodes
)
{
node
.isOpen
= this.isOpen
;
}
CurrentNode
= this;
CurrentNode
.childNodes
= this.childNodes
;
}
}
private IEnumerator CotainerSiwtch(bool open
, BaseNode nodes
)
{
if (this.parentRectTransform
!= null)
{
float t
= 0;
float targetValue
= open
? EndContainerWidth
: StartContainerWidth
;
while (t
< EleasticSpeed
)
{
yield return null;
float value = Mathf
.Lerp(nodes
.parentRectTransform
.sizeDelta
.x
, targetValue
, t
/ EleasticSpeed
);
t
+= Time
.deltaTime
;
nodes
.parentRectTransform
.sizeDelta
= new Vector2(value, nodes
.parentRectTransform
.sizeDelta
.y
);
}
}
}
Demo地址,扫下方码->历史消息->找到当前文章末尾即可获取
更多内容,欢迎访问:
转载请注明原文地址: https://mac.8miu.com/read-503649.html