1
\$\begingroup\$

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;
     }
 }

Material Screenshot

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – Stephen George Oct 27 '16 at 0:58
  • \$\begingroup\$ And I also get the "MissingComponentException" error because the material I assigned is not longer there whenever I start Play Mode. \$\endgroup\$ – Stephen George Oct 27 '16 at 1:01
  • \$\begingroup\$ This should work: GetComponent<Renderer>().material.shader = yourshader \$\endgroup\$ – CiscoIPPhone Oct 27 '16 at 14:54
  • \$\begingroup\$ 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 \$\endgroup\$ – Stephen George Oct 27 '16 at 17:27
  • \$\begingroup\$ That does sound like a new question @StephenGeorge \$\endgroup\$ – CiscoIPPhone Oct 27 '16 at 18:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.