using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[ExecuteInEditMode]
public class ChangeShaderMono : MonoBehaviour
{
private GameObject selectedObject;
private List<Transform> selectedobjects;
private GameObject selectonce;
public void SelectedObject()
{
selectedObject = Selection.activeGameObject;
if (selectonce != selectedObject)
{
selectedobjects = new List<Transform>();
Transform[] allChildren = selectedObject.GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren)
{
if (child.gameObject.GetComponent<MeshRenderer>().sharedMaterial != null)
{
var mat = child.gameObject.GetComponent<MeshRenderer>().sharedMaterial;
selectedobjects.Add(child);
}
}
}
selectonce = selectedObject;
}
private void Update()
{
SelectedObject();
}
}
问题出在IF行上:
if (child.gameObject.GetComponent<MeshRenderer>().sharedMaterial != null)
如果游戏对象没有材质,它将在此行引发异常,并且不会继续。我想获取所有带有已附加材质的子级游戏对象,包括选定的父级游戏对象。
private void Find(GameObject parent, ref System.Collections.Generic.List<GameObject> result)
{
var spriteRenderer = parent.GetComponent<SpriteRenderer>();
var meshRenderer = parent.GetComponent<MeshRenderer>();
var image = parent.GetComponent<UnityEngine.UI.Image>();
if (spriteRenderer != null && spriteRenderer.material != null)
{
result.Add(parent.gameObject);
}
else if (meshRenderer != null && meshRenderer.material != null)
{
result.Add(parent.gameObject);
}
else if (image != null && image.material != null)
{
result.Add(parent.gameObject);
}
foreach (Transform child in parent.transform)
{
Find(child.gameObject, ref result);
}
}
public void SelectedObject()
{
if (UnityEditor.Selection.activeGameObject != null)
{
var result = new System.Collections.Generic.List<GameObject>();
Find(UnityEditor.Selection.activeGameObject, ref result);
}
}