How to change a child's shader to another shader?

Hello,

So I’ve got some objects I’ve created on the fly representing my player’s units. I’d like to change the unit’s color based on who the unit belongs to. I’ve created a dark purple shader and tried applying it to the child object of my script like such:

this.gameObject.transform.GetChild (0).GetComponent<Renderer> ().materials [0].shader = Shader.Find ("PlayerTwo");

Unfortunately the code above changes the cube to a bright pink color. I’ve tried other colors (red, orange, etc…) to make sure it isn’t a lighting problem… but to no avail.

Example cube: http://nerd.guru/paste/Unity_2016-03-19_21-17-50.png

What am I doing wrong?

Hi,

Bright pink means shader error. Look in your console. Most probably it cannot find the shader by the name you specified.

However, instead you should pre-make all kinds of materials you are going to use in the scene, set up all the colors and variables, and in runtime you call this on the child object:

.GetComponent().sharedMaterial = thatPremadeMaterialYouMade;