分享一个在Unity中控制代码,只显示选中物体和Camera还有挂载本脚步的物体
使用方法:在场景中添加一个空物体,挂载本脚本即可。
实现很简单,
1.获取本场景所有物体。
public List<GameObject> list;
public void Init()
{
list = new List<GameObject>();
GameObject[] all = Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[];
for (int i = 0; i < all.Length; i++)
{
var item = all[i];
if (item.scene.isLoaded)
{
list.Add(all[i]);
}
}
}
2.遍历所有list,通过isOtherShow来制定是否显示。
3.通过Selection.activeObject判断是否选中物体,定义GameOvject数组show接收Selection.gameObjects获取所有选中的物体。
4.显示对象所有父结点。
public void ShowParent(GameObject obj)
{
try
{
while (obj != null)
{
obj.SetActive(true);
obj = obj.transform.parent.gameObject;
}
}
catch
{
obj.SetActive(true);
}
}
需要try catch一下 否则到根结点回抱空。
5.显示对象所有子节点,
public void ShowChild(GameObject obj)
{
foreach (Transform g in obj.GetComponentsInChildren<Transform>(true))
{
//Debug.Log(obj.GetComponentsInChildren<Transform>(true).Length);
g.gameObject.SetActive(true);
}
}
注意在GameObject.GetComponentsInChildren(true)括号内填true,可以获取未激活(显示)物体,包括本身
若为false则只获取激活(显示)的物体,包括本身,
不填写默认为false
下面为完整代码
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
//[ExecuteInEditMode]为编辑器模式下可运行
//[ExecuteInEditMode]
public class OnlyShowObj : MonoBehaviour
{
public List<GameObject> list;
public GameObject[] show;
public bool isOtherShow = false;
void Start()
{
Init();
}
public void Init()
{
list = new List<GameObject>();
GameObject[] all = Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[];
for (int i = 0; i < all.Length; i++)
{
var item = all[i];
if (item.scene.isLoaded)
{
list.Add(all[i]);
}
}
}
void Update()
{
Init();
for (int i = 0; i < list.Count; i++)
{
if (!(list[i] == gameObject || list[i].GetComponent<Camera>() != null))
{
list[i].SetActive(isOtherShow);
}
}
if (Selection.activeObject != null)
{
show = new GameObject[Selection.gameObjects.Length];
show = Selection.gameObjects;
for (int i = 0; i < show.Length; i++)
{
ShowParent(show[i]);
ShowChild(show[i]);
}
}
}
public void ShowParent(GameObject obj)
{
try
{
while (obj != null)
{
obj.SetActive(true);
obj = obj.transform.parent.gameObject;
}
}
catch
{
obj.SetActive(true);
}
}
public void ShowChild(GameObject obj)
{
foreach (Transform g in obj.GetComponentsInChildren<Transform>(true))
{
//Debug.Log(obj.GetComponentsInChildren<Transform>(true).Length);
g.gameObject.SetActive(true);
}
}
}
小白一个,有说的不对的地方欢迎指出。
希望对大家有帮助。