I want to add the script to each gameobject child. Not the gameobject but to it’s child.
List<GameObject> cubes = new List<GameObject>();
Then
foreach (GameObject go in cubes)
{
go.AddComponent<BoxCollider>();
go.AddComponent<mouseDrag>();
}
But this will add the script mouseDrag to the gameobjects not to the children.
Every GameObject in the List have a child cube gameobject.
For example in cubes[0] there is a child Cube. And i want to add the script to the Cube.
Same for all gameobjects in the list.
There are different ways. You could use getChild. Or you can loop through the transforms.
Typed in the forum, so it may not be perfect caps/format, but should give you the idea. Since you have a list of cubes, you’d have to put this inside your foreach and then loop through the cubes children.
NOTE: If you only have one child, you can just use cube.transform.getChild(0); to get that child.
foreach(Transform child in cube.transform)
{
child.AddComponent<newScript>();
}
int childCount = cube.transform.childCount;
for(int x = 0; x < childCount;x++)
{
cube.transform.getChild(x).AddComponent<newScript>();
}
‘Transform’ does not contain a definition for ‘AddComponent’ and no extension method ‘AddComponent’ accepting a first argument of type ‘Transform’ could be found (are you missing a using directive or an assembly reference?)