简体   繁体   中英

GetComponentInChildren with child index when there are multiple child objects

How can I select from which child I want to get a component from using .GetComponentInChildren when I have multiple child objects?

With this code I get the MeshRenderer of the first child only.

 selectedObj.GetComponentInChildren<MeshRenderer>().material.SetColor("_EmissionColor", Color.red);

If you know the unique name of the child object that has the component you are after, you can use transform.FindChild("nameOfChildObject") to find the specific child object you are looking for. So in your case you could say:

selectedObject.transform.FindChild("nameOfChildObject").GetComponent<MeshRenderer>().material.SetColor("_EmissionColor", Color.red);

GetComponentInChildren cannot do this. You can do that with the index of the child GameObject with the help of the GetChild function. The code below will get component of a child GameObject with the index of 3.

int CHILD_INDEX = 3;
selectedObj.transform.GetChild(CHILD_INDEX).GetComponent<MeshRenderer>().material.SetColor("_EmissionColor", Color.red);

Make custom generic extension method for this and add index parameter to the GetComponentInChildren function:

public static class ExtensionFunction
{
    public static T GetComponentInChildren<T>(this GameObject gameObject, int index)
    {
        return gameObject.transform.GetChild(index).GetComponent<T>();
    }
}

Then you can now do:

int CHILD_INDEX = 3;
selectedObj.GetComponentInChildren<MeshRenderer>(CHILD_INDEX).material.SetColor("_EmissionColor", Color.red);

Using FindChild each time you just want to get component from a child GameObject will only slow down your game especially if you do a lot.

This worked for me:

MeshRenderer[] var = selectedObj.GetComponentsInChildren<MeshRenderer>;
foreach (material m in var)
{
   m.SetColor("_EmissionColor", Color.red);
}

Then i just loop var to modify each object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM