Hello guys.
I am trying to change the color of children of Instantiated prefab to the color of gameobject which is clicked.
Suppose prefab1 contains gameobject2,gameobject3 which are spheres and gameobject4 which is a clyinder.
GameObject1 which again is a sphere(red colored) when clicked should instantiate the prefab and color of gameobject2,3,4 should be red colored.
I am able to instantiate the prefab on click of the Gameobject1 using raycasting so what is supposed to be done next ? Tried something like this:
GameObject go = (GameObject)Instantiate(Resources.Load(“Gameobject”));
go.name=“first”;
GameObject.Find(“first”).renderer.material.color=col1;
GetComponentsInChildren will give you an array of all components of this type within all direct children of the game object you call it on.
So first you have to make sure you can find your prefab instance, e.g. lets say by giving it the name “prefab” and use GameObject.Find("prefab")
. (Other ways would include using Tags or assigning it to a public variable in the editor inspector).
so it should be in a for loop - something like this (C#):
var prefab = GameObject.Find("prefab"); // prefab instance must be named "prefab"
var first = ...; // instantiate your "first" object with the red sphere
var col1 = first.renderer.material.color; // get its color
foreach (var child in first.GetComponentsInChildren<Renderer>())
child.material.color = col1;