About retrieving components that do not retain child objects

Asked 1 years ago, Updated 1 years ago, 36 views

I wanted to get the Render component of the child object by placing the following script on the parent object:
However, not all child objects have Render components, so the MissingComponentException came out.

 void GetMaterial (GameObject gameobject)
{

    if(gameObject.GetComponent<Render>()?.material!=null)
    {
        _materials.Add(gameObject.GetComponent<Render>().material);
    }

    foreach(Transform child in gameObject.GetComponents<Transform>())
    {
        GetMaterial (child.gameObject);
    }
}

How can I implement only objects with Renderer components without errors?
I look forward to hearing from you.

c# unity3d

2022-09-29 22:42

1 Answers

In the Unity editor, the GetComponent result is fake null.
Fake null is actually not null because it overloaded the comparison operator.
Then, you can get MissingComponentException instead of NullReferenceException in the editor.
The null operator is different from the == and != operators.Unable to overload.

 void GetMaterial (GameObject gameobject)
{
    var render=gameObject.GetComponent<Render>();

    if(render!=null&render.material!=null)
    {
        _materials.Add(render.material);
    }

    foreach (Transform child in gameObject.transform)
    {
        GetMaterial (child.gameObject);
    }
}

It's hard to explain in Japanese.


2022-09-29 22:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.