今天在社区正好看到个相关问题,简单写了写就记录一下,Hierarchy实际上是一种树型结构,所以可以构建数据结构存储子节点(比如BFS遍历每一层),也可以只保存节点的父物体信息(递归)。
using
System
.
Collections
;
using
System
.
Collections
.
Generic
;
using
UnityEngine
;
public
class
TestHierarchy
:
MonoBehaviour
{
public
Transform
parent
;
private
Dictionary
<
Transform
,
Transform
>
parentDic
=
new
Dictionary
<
Transform
,
Transform
>
(
)
;
void
Start
(
)
{
DetachAllChildren
(
parent
)
;
}
void
Update
(
)
{
if
(
Input
.
GetKeyDown
(
KeyCode
.
A
)
)
{
DetachAllChildren
(
parent
,
true
)
;
}
if
(
Input
.
GetKeyDown
(
KeyCode
.
B
)
)
{
GetBack
(
)
;
}
}
void
DetachAllChildren
(
Transform
temp
,
bool
isDetach
=
false
)
//递归解除所有的父子关系
{
if
(
temp
.
childCount
==
0
)
{
if
(
!
isDetach
)
{
parentDic
[
temp
]
=
temp
.
parent
;
}
return
;
}
for
(
int
i
=
0
;
i
<
temp
.
childCount
;
i
++
)
{
if
(
!
isDetach
)
{
parentDic
[
temp
]
=
temp
.
parent
;
}
DetachAllChildren
(
temp
.
GetChild
(
i
)
,
isDetach
)
;
}
if
(
isDetach
)
{
temp
.
DetachChildren
(
)
;
}
}
void
GetBack
(
)
{
foreach
(
Transform
item
in
parentDic
.
Keys
)
{
item
.
SetParent
(
parentDic
[
item
]
)
;
}
}
}
代码的核心实际就是一次递归DFS,在Start里先进行一次没有实际Detach操作的深搜来获取所有,再Update触发Detach逻辑是解除所有关系,并在GetBack里按照存储的信息还原即可。
