通过GameObject的名字查找方法,传入查找的对象与名字,不管是父集还是子集,都可以使用
public static GameObject FindGameObjectByName(GameObject obj,string name)
{
if(obj == null)
return null;
GameObject findObj = null;
if(obj.name == name)
{
findObj = obj;
return findObj;
}
for(int i = 0; i < obj.transform.childCount; ++i)
{
findObj = FindGameObjectByName(obj.transform.GetChild(i).gameObject,name);
if(findObj != null)
{
return findObj;
}
}
return null;
}
设置对象包括对象子集的层级的方法
public static void SetGameObjectLayer(GameObject obj,int layer)
{
if(obj == null)
return;
obj.layer = layer;
for(int i = 0; i < obj.transform.childCount; ++i)
{
SetGameObjectLayer(obj.transform.GetChild(i).gameObject,layer);
}
}
设置对象是否显示的方法
public static void SetGameObjectRenderState(GameObject obj,bool b)
{
if(obj == null)
return;
obj.GetComponent<Renderer>().enabled = b;
for(int i = 0; i < obj.transform.childCount;++i)
{
SetGameObjectRenderState(obj.transform.GetChild(i).gameObject,b);
}
}
对象的本地坐标与世界坐标相互转换的方法
public static Vector3 LocalPosToWorldPosForGameObject(GameObject obj,Vector3 pos)
{
Vector3 worldPos = pos;
if(obj.transform.parent != null)
{
worldPos.x = obj.transform.parent.localPosition.x + worldPos.x*obj.transform.parent.localScale.x;
worldPos.y = obj.transform.parent.localPosition.y + worldPos.y*obj.transform.parent.localScale.y;
worldPos.z = obj.transform.parent.localPosition.z + worldPos.z*obj.transform.parent.localScale.z;
worldPos = LocalPosToWorldPosForGameObject(obj.transform.parent.gameObject,worldPos);
}
return worldPos;
}
public static Vector3 WorldPosToLocalPosForGameObject(Camera mainCamera,Camera NGUICamera, Vector3 pos)
{
Vector2 screenPos = mainCamera.WorldToScreenPoint(pos);
Vector3 loaclPos = NGUICamera.ScreenToWorldPoint(screenPos);
return loaclPos;
}
删除所有子集对象的方法
public static void DestroyGameObjectAllChildrens(GameObject obj)
{
if(obj == null)
{
return;
}
if(obj.transform.childCount == 0)
{
return;
}
int count = obj.transform.childCount;
for(int i = 0; i < count;++i)
{
GameObject child = obj.transform.GetChild(i).gameObject;
if(child != null)
{
GameObject.DestroyImmediate(child);
}
}
}
修改对象的父集方法
public static void GameObjectAttachToParent(GameObject obj,GameObject parentObj,bool useSelfScale = false)
{
float selfScaleX = obj.transform.localScale.x;
float selfScaleY = obj.transform.localScale.y;
float selfScaleZ = obj.transform.localScale.z;
obj.transform.parent = parentObj.transform;
obj.transform.localPosition = Vector3.zero;
obj.transform.localRotation = Quaternion.identity;
if(!useSelfScale)
{
obj.transform.localScale = new Vector3(1,1,1);
}
else
{
obj.transform.localScale = new Vector3(selfScaleX,selfScaleY,selfScaleZ);
}
obj.layer = parentObj.layer;
}