- Home /
Adding a Color Change Script to a Model
Having a previous question of mine answered on here I was able to obtain a script that changed the colors of the materials on a model I attached it to. It works like it should and I thank he who showed me. However there is something I don't understand. I have 2 tree models. Model A, I apply the script too, and the material for the Bark of the tree changes color, not the leaves. (I want the leaves to change.) Model B I change it to, and it changes the colors of the leaves, not the bark. So why is it working differently with different models? The only thing I can think of myself is that when I click on each tree and look at the Inspector, it shows the materials on the model. Model A has 2 materials, the first one it shows is that bark. Model B also has 2 models, the first one it shows is the leaves. Does it only apply to the first material shown? And if this is the problem, how can I get it to attach to the material I want? Any help is appreciated.
Follow up: You can attach the script that changes the renderer.materials[i] to a tree, then make a prefab of that tree, and then place the prefab. This will mean that any new tree you place will change color in the same way. Additional question: How do you change the Emissive color or Spec color through scripting? I can only change the "main" color ....
Answer by qJake · Sep 14, 2010 at 02:28 AM
You need to use the array renderer.materials[]. The code renderer.material is just a shortcut for renderer.materials[0], accessing the "first" material, but they aren't in a specific order.
Oh wow that worked perfectly thanks! So another thing quick, I attached this script to the tree, now the leaves are changing color back and forth like they should. Is there any way to use this tree as a Brush so I can put down a lot of them and have them still keep the script? Or will I have to place them one by one?
Once again, this should be commented to the answer that it refers to, not posted as a separate answer.
Wont work on painted (Terrain trees)
http://answers.unity3d.com/questions/26985/changing-color-of-tree-material.html
Thanks for the answer qJake. By changing to renderer.materials[1].color I can now change the color of the leaves on my tree.
For some unknown reason, the trunk color is also being changed. Any idea of why and/or how to only change the leaf color?
The model I'm using is the Alder that comes with Unity's Terrain Assets import. There is a mesh renderer with a materials indent menu with: Size(2) Element 0 (alder-alderbark) Element 1 (alderbranches)
Then below all other components the two elements appear with shader options.
The alderbranches is the leaf texture.
So somehow the random color generated for the trunk was saved to the prefab... thats why it appeared the trunks were different colors too. Everything is working fine now that I changed the prefab trunk color back to default white. =).