Changing material/shader at runtime (C# scripting)

Hi,

what I’d like to do is pretty simple but it doesn’t seem to work.

I have a 3D model with a material with a Self-Illumin/Diffuse shader.
At some point at runtime I just want to change the shader to Transparent/Diffuse in order to fade out the model.

I tried to do it different ways :

1 - Using Shader.Find()

// Declaration
Shader transparent;

// Finding shader in Awake()
transparent = Shader.Find("Transparent/Diffuse");

// Changing  shader
3dmodel.renderer.material.shader = transparent;

2 - Using a public material

// Declaration
public Material mat_transparent; // Material with a Transparent/Diffuse shader assigned in Inspector

// Changing material
3dmodel.renderer.material = mat_transparent;

I tried in many ways, using 3dmodel.renderer``3dmodel.GetComponent<MeshRenderer>()``3dmodel.GetComponentInChildren<MeshRenderer>()``3dmodel.GetComponent<Renderer>()``3dmodel.GetComponentInChildren<Renderer>()but none of them is woking…

The code I’m running to change the shader/material is in a coroutine.
Am I doing something wrong ?

Seems like it should work… at least it’s similar to the docs:

Maybe you check your code again for some missing stuff, spelling mistakes or whatever?

Well, I already double, triple-checked my code searching for mistakes I could’ve done writing it, but nope, it should work. :confused:

I expect the problem has nothing to do with the code you are showing. For the testing you may write a script that changes the shader/material, but not in a coroutine, such that you get something that works and then integrate that into the coroutine.

1 Like

I solved the problem.

When I wanted to switch the shader, I was calling a function from a coroutine.

What I’m doing now is that I’m testing a boolean in the Update(), and I’m updating it in the coroutine, and, depending on it’s state, i’m calling the function to switch to transparent shader or switch back to the original one.

2 Likes

HI Can help me. I have scene where have number of game object. Need to be behind transperent object should show. but should not have any click or other event should to fire. shall we able to do it. if so, please let me know.

1 Like

omg thanks so much! keeping it outside the coroutine solved it for me too! :slight_smile:

Hi, helped me as well! Thank’s!
Besides that I do not understand it :eyes: I am trying to keep my update-function as small as possible and I can’t see any reason why it should not be possible to change the shader in coroutine … anyway. Can’t change it, so moving on with my life :smile:

Hi :slight_smile: Glad you solved. Can I know how you did it ? Thanks