- Home /
How do I restore a shader after a raycast?
Hi. If I change the transparency of a shader once it is hit by a raycast using the code below, how can I restore it after it is no longer being "hit" by the raycast?
void Update() {
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, 10))
{
//changes the shader and transparency
hit.collider.renderer.material.shader = Shader.Find("Transparent/Diffuse");
Color color = hit.collider.renderer.material.color;
color.a = 0.5f;
hit.collider.renderer.material.color = color;
}
Answer by DaveA · Jan 21, 2011 at 06:32 AM
Save the hit collider in a local var, and add an 'else' clause which restores it. You may want a 'sentinal' boolean or something (or just use said var) to test that it was 'just hit' or 'just un-hit' so you don't have to reset it on every frame.
Hmm, so something like this?
Collider hitCollider;
if (){ ... hitCollider = hit.collider; }
else { Color color = hit.collider.renderer.material.color; color.a = 1; hitCollider.renderer.material.color = color }
Something like that. You may want to add: .... else { if (hitCollider) { .. reset color/alpha ..; hitCollider = null; } Testing hitCollider for non-null, and setting to null after using it, ensures that the reset only happens once, not every frame.
Your answer
![](https://koobas.hobune.stream/wayback/20220613100417im_/https://answers.unity.com/themes/thub/images/avi.jpg)