- Home /
Why does my code have no effect on the materials color?
I create some game objects from a prefab and want to set individual colors per player. The debug statement is executed, but I can't see that the color is changing.
void setColor( GameObject go, VRPlayer vrp ) {
Renderer rend = go.GetComponent<Renderer>();
Shader shader = Shader.Find("Diffuse");
Material[] mat = rend.materials;
for ( int i = 0 ; i < mat.Length ; i++ ) {
if ( mat[i].name.StartsWith("PlatformYellow")) {
mat[i] = new Material( shader );
mat[i].color = vrp.col;
Debug.Log("found and assigned color=" + vrp.col );
break;
}
}
}
I also tried to reuse the shader (Line 8, in case I failed to setup the shader correctly)
mat[i] = new Material( mat[i].shader );
According to the documentation something like this should work:
mat[i].SetColor("_Color", vrp.col );
Would it be possible to get some upvotes so that I reach the 15 rep limit, it takes many hours until my questions have been reviewed. Thanks!
Comment
Best Answer
Answer by stacker3d · Apr 09, 2015 at 10:58 AM
The materials array needs to be re-assigned to get applied. Probably the wrapper will do some extra work when the modified array is assigned:
mat[i] = new Material( shader );
mat[i].color = vrp.col;
rend.materials = mat; // <- this extra assignment is required