我如何获得所有附有物质成分的游戏对象的列表?

问题描述 投票:0回答:1
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)

如果游戏对象没有材质,它将在此行引发异常,并且不会继续。我想获取所有带有已附加材质的子级游戏对象,包括选定的父级游戏对象。

c# unity3d
1个回答
0
投票
  • 您可以在下面尝试。
  • 代码将递归查找所有子代,
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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.