# Change Shader on This Material Via Code?

How do I change this material to have the Toon/ Lit Outline shader via code at the Start of the scene?

Here is my code that I have as of now, that does not work:

 using UnityEngine;
using System.Collections;

public class MainMenuManager : MonoBehaviour
{
public Material hatMaterial;    //This is my character's hat shader - I set this in the Inspector

private Shader toonShader;    //This is the Toon Shader with an Outline

void Start ()
{
toonShader = GetComponent<Shader> ();

toonShader = Shader.Find ("Toon/Lit Outline");

hatMaterial = GetComponent<Material> ();

hatMaterial.shader = toonShader;
}
}


## 1 Answer

GetComponent retrieves Components, shader isn't a component (it doesn't inherit from component) so GetComponent won't work.

However, your code still looks fine (that first GetComponent line can be deleted).

It could be due to how you're assigning the hatMaterial - did you drag it from the project view? If so that could be the problem because materials are instanced when the game starts so essentially you'd be modifying another material. If that is the case you'd need to fix it by dragging the specific material being used in the scene OR you could get a instance of a renderer, and use its sharedMaterial property to modify all instances of the material.

• Yes the way I am assigning "hatMaterial" is by dragging the material from the Project Panel into the variable slot I made for it. And whenever the game starts, the hatMaterial I dragged into that slot disappears and it says "None (Material)". I know that is my problem! @CiscoIPPhone Oct 27 '16 at 0:58
• And I also get the "MissingComponentException" error because the material I assigned is not longer there whenever I start Play Mode. Oct 27 '16 at 1:01
• This should work: GetComponent<Renderer>().material.shader = yourshader Oct 27 '16 at 14:54
• I completely changed the way I approached this last night. I have a question regarding my "for" loop that i created that involves my new approach. Must I post this as a new question? @CiscoIPPhone Oct 27 '16 at 17:27
• That does sound like a new question @StephenGeorge Oct 27 '16 at 18:09