Last active
March 12, 2024 13:09
-
-
Save dmitry1100/96c1eb7323d83e4f8d00cb6844bbd09a to your computer and use it in GitHub Desktop.
Unity Transform extension to enumerate all nested children deeply
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
namespace Fiftytwo | |
{ | |
public static class TransformAllChildren | |
{ | |
public static IEnumerable<Transform> AllChildren ( this Transform t ) | |
{ | |
return new DeepEnumerator( t ); | |
} | |
private class DeepEnumerator : IEnumerator<Transform>, IEnumerable<Transform> | |
{ | |
private readonly Transform _root; | |
private Transform _current; | |
private Stack<Transform> _stack; | |
internal DeepEnumerator ( Transform root ) | |
{ | |
_root = root; | |
_current = root; | |
_stack = new Stack<Transform>(); | |
} | |
public Transform Current { get { return _current; } } | |
object IEnumerator.Current { get { return _current; } } | |
void IDisposable.Dispose () { } | |
public bool MoveNext () | |
{ | |
for( var i = _current.childCount; --i >= 0; ) | |
_stack.Push( _current.GetChild( i ) ); | |
if( _stack.Count == 0 ) | |
return false; | |
_current = _stack.Pop(); | |
return true; | |
} | |
public void Reset () | |
{ | |
_current = _root; | |
_stack.Clear(); | |
} | |
public IEnumerator<Transform> GetEnumerator () | |
{ | |
Reset(); | |
return this; | |
} | |
IEnumerator IEnumerable.GetEnumerator () | |
{ | |
return GetEnumerator(); | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
namespace Fiftytwo | |
{ | |
public class TransformAllChildrenTest : MonoBehaviour | |
{ | |
// Will be called just after component attached to GameObject | |
private void Reset () | |
{ | |
foreach ( var child in transform.AllChildren() ) | |
{ | |
Debug.Log( child.name ); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment