Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Changing shader at runtime?

Discussion in 'Scripting' started by KidNova, Feb 11, 2016.

  1. KidNova

    KidNova

    Joined:
    Dec 28, 2015
    Posts:
    13
    So I've been looking on the internet on how to change a shader at runtime (whenever an object is clicked), and Unity seems to be crashing everytime I try to change the shader.

    Here's my code:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class SetAlive : MonoBehaviour {
    5.  
    6.     public bool alive;
    7.     Renderer rend;
    8.     Shader deadShader;
    9.     Shader aliveShader;
    10.  
    11.     void Start () {
    12.         rend = GetComponent<Renderer>();
    13.         deadShader = Shader.Find("PurpleShader");
    14.         aliveShader = Shader.Find("GreenShader");
    15.     }
    16.  
    17.     void OnMouseDown()
    18.     {
    19.         if (alive)
    20.         {
    21.             alive = false;
    22.             rend.material.shader = Shader.Find("PurpleShader");
    23.         }
    24.  
    25.         else
    26.         {
    27.             alive = true;
    28.             rend.material.shader = Shader.Find("GreenShader");
    29.         }
    30.     }
    31. }
    Not really sure what I'm doing wrong for Unity to just crash whenever the object is clicked? I would just switch the gameobject out when clicked instead of changing the shader, but it's important for me to keep the same object and keep them ordered. If anyone has any insight, thanks!
     
  2. Laperen

    Laperen

    Joined:
    Feb 1, 2016
    Posts:
    1,065
    KidNova likes this.