[小技巧] 如何保存Hierarchy层级关系并进行恢复

这篇博客介绍了如何在Unity中通过递归方式解除所有子物体的父子关系,并能根据存储的信息还原。核心代码实现了一次深度优先搜索(DFS),在Start时记录原始关系,Update时按需求解除关系,GetBack方法则根据记录恢复原状。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在社区正好看到个相关问题,简单写了写就记录一下,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里按照存储的信息还原即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值