- Home /
Changing shaders in a game during runtime
So the basic idea I want in my game is any "Environment" object in the way between the player and the camera to change to a transparent shader so you can see the player. I have the raycast correctly calculating the buildings. I also want to revert back to the original shader once the raycast is not touching the object anymore. I have a shader that makes objects transparent, however once I apply the shader to the Environment object it turns pink and I am unsure why.
Here's the code I have so far in my FixedUpdate function:
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 fwd = transform.TransformDirection(Vector3.forward);
Debug.DrawRay(transform.position, Vector3.forward);
if (Physics.Raycast(transform.position, fwd, out hit))
{
if (hit.collider.gameObject.tag == "Environment")
{
Transform objectHit = hit.transform;
objectHit.GetComponent<Renderer>().material.shader = Shader.Find("ToonLitOutlineTransparent");
Debug.Log("Building has been hit");
}
}
I am unsure how to solve this problem and any help would be appreciated.
EDIT: Just an FYI when i drag the shader through in my scene view, it works fine. It just turns pink at runtime so I assume there is a conflicting error.
Pink color shows a shader compile error. A good way might be to change material ins$$anonymous$$d of just the shader.
So ins$$anonymous$$d of calling the shader, create a material with the shader on and use that?
Answer by mgear · Apr 03, 2018 at 05:58 AM
If its pink in build, that could mean shader is not included in the build. Can assign it to Always included shaders from Edit/Project Settings/Graphics other ways of always including it: https://docs.unity3d.com/ScriptReference/Shader.Find.html
Otherwise could also check if the Shader.Find returns null.
Your answer
Follow this Question
Related Questions
Rotating player relative to the camera (Unity C#) 1 Answer
How to : Apply shader only on camera for certain layer of UI 0 Answers
How to detect if an object is within another object??? (Hide and seek type game). Thanks! 2 Answers
Render object with different shader depending on the camera 2 Answers
What is the procedure of capturing a particular region using Render Texture 0 Answers