using UnityEngine;
///
/// Transform组件助手类
///
public static class TransformHelper
{
///
/// 面向目标方向
///
/// 目标方向
/// 需要转向的对象
/// 转向速度
public static void LookAtTarget(Vector3 targetDirection, Transform transform, float rotationSpeed)
{
if (targetDirection != Vector3.zero)
{
var targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotationSpeed);
}
}
///
/// 查找子物体(递归查找)
///
/// 父物体
/// 子物体的名称
/// 找到的相应子物体
public static Transform FindChild(Transform trans, string goName)
{
if (goName == trans.name)
return trans;
Transform child = trans.Find(goName);
if (child != null)
return child;
Transform go = null;
for (int i = 0; i < trans.childCount; i++)
{
child = trans.GetChild(i);
go = FindChild(child, goName);
if (go != null)
return go;
}
return null;
}
/// 获取所有的孩子
/// 父物体位置
/// 所有子物体数组
public static Transform[] GetChilds(Transform parent)
{
Transform[] childs = new Transform[parent.childCount];
for (int i = 0; i < childs.Length; i++)
childs[i] = parent.GetChild(i);
return childs;
}
///
/// 删除所有孩子
///
/// 父物体位置
public static void DelChilds(Transform parent)
{
for (int i = 0; i < parent.childCount; i++)
Object.Destroy(parent.GetChild(i).gameObject);
}
///
/// 设置所有孩子Active
///
/// 父物体位置
public static void SetActiveChilds(Transform parent, bool isActive)
{
for (int i = 0; i < parent.childCount; i++)
parent.GetChild(i).gameObject.SetActive(isActive);
}
///
/// 查找父对象
///
/// 子物体位置
/// /// 父物体名称
public static Transform FindParentByName(Transform trans, string goName)
{
Transform pTrans = null;
if (trans.parent)
{
Transform pobj = trans.parent;
if (pobj.name == goName)
{
pTrans = pobj;
}
else
{
pTrans = FindParentByName(pobj, goName);
}
}
return pTrans;
}
///
/// 查找父对象
///
/// 子物体位置
/// /// 父物体名称
public static Transform FindParentByTag(Transform trans, string tagName)
{
Transform pTrans = null;
if (trans.parent)
{
Transform pobj = trans.parent;
if (pobj.tag == tagName)
{
pTrans = pobj;
}
else
{
pTrans = FindParentByTag(pobj, tagName);
}
}
return pTrans;
}
///
/// 设置对象包含子对象的Layer
///
/// 对象
/// 新的Layer
public static void SetLayerRecursively(GameObject obj, int newLayer)
{
obj.layer = newLayer;
foreach (Transform child in obj.transform)
{
SetLayerRecursively(child.gameObject, newLayer);
}
}
public static void SetRenderer(GameObject obj, bool enable)
{
var renderer = obj.GetComponent();
if (renderer)
{
renderer.enabled = enable;
}
foreach (Transform child in obj.transform)
{
SetRenderer(child.gameObject, enable);
}
}
}