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.
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.
© 2024 OneMinuteCode. All rights reserved.