///
/// MIT License - Copyright(c) 2019 Ugo Belfiore
///
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public static class ExtTransform
{
///
/// Remove every childs in a transform
/// use: someTransform.ClearChild();
/// someTransform.ClearChild(true); //can destroy immediatly in editor
///
public static Transform ClearChild(this Transform transform, bool immediate = false)
{
if (Application.isPlaying)
{
foreach (Transform child in transform)
{
GameObject.Destroy(child.gameObject);
}
}
#if UNITY_EDITOR
else if (immediate)
{
if (UnityEditor.PrefabUtility.IsPartOfPrefabInstance(transform))
{
Debug.Log("here we are in a prefabs !!!!!");
GameObject rootPrefabs = UnityEditor.PrefabUtility.GetOutermostPrefabInstanceRoot(transform);
if (rootPrefabs == null)
{
return (transform);
}
string pathRootPrefabs = UnityEditor.PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(rootPrefabs);
Debug.Log(pathRootPrefabs);
UnityEditor.PrefabUtility.UnpackPrefabInstanceAndReturnNewOutermostRoots(rootPrefabs, UnityEditor.PrefabUnpackMode.Completely);
var tempList = transform.Cast().ToList();
foreach (var child in tempList)
{
GameObject.DestroyImmediate(child.gameObject);
}
UnityEditor.PrefabUtility.SaveAsPrefabAssetAndConnect(rootPrefabs, pathRootPrefabs, UnityEditor.InteractionMode.UserAction);
}
else
{
var tempList = transform.Cast().ToList();
foreach (var child in tempList)
{
GameObject.DestroyImmediate(child.gameObject);
}
}
}
#endif
return (transform);
}
///
/// return a list of all child in a transform (not recursive)
/// use: List() newList = someTransform.GetAllChild();
///
///
///
public static List GetAllChild(this Transform transform)
{
List allChild = new List();
foreach (Transform child in transform)
{
allChild.Add(child);
}
return (allChild);
}
}