- Home /
Changing the material of all children, then change back to old one
im trying to change the material of every child to certain shader when using a cloaking device, then when the device is off reassign the old one
this function is on the cloak device on the player and switches all of the materials to the cloak one:
var cloakMat : Material;
function CloakMaterial () {
var allChildren = transform.parent.gameObject.GetComponentsInChildren(Transform);
for (var child : Transform in allChildren)
{
if(child.renderer != null)
{
child.renderer.material = cloakMat;
}
}
}
my problem is trying to make an array filled with all of the old materials and putting them back
or should i try to just put the cloak material in the built in "materials" array in the renderer component and then switch back and forth from there?(this would probably be a lot more work for me and i would prefer not to)
another solution would be to add the cloak material at the end of the index for the built in materials array
then i could maybe switch back to the previous array number to switch the material back
i still kinda need help carrying that out though...
Answer by supernat · Sep 16, 2013 at 01:53 AM
In the Start() method, you should create a new material array, then assign the existing material before cloaking it, something like follows (sorry my JS is very rusty, so this is in C# but should be easy to transpose):
Material[] prevMats;
void Start()
{
prevMats = new Material[transform.parent.childCount];
}
Since we need to keep the materials ordered, we can just create an index variable and set it to 0 outside of the for() loop in your CloakMaterial() method. Now, the caveat is that I am assuming your transforms will always be returned in the same order. This should generally be acceptable as long as you aren't creating/destroying transforms dynamically. If you see the wrong textures applied after coming back from a cloak, it means the index no longer matches what it did when you saved the material off. Then we can use a Dictionary or some other method to associate each child transform with its material.
Then, just above the child.renderer.material = cloakMat, add the following line:
prevMats[indx++] = child.renderer.material;
Now, create a ReturnToNormal() method that rotates through the children and sets their materials back to prevMats[indx++] in the same way.
thanks for such a detailed response, pretty sure i can handle it with this info, thanks a lot! :)