Change Rendering Mode via Script

So I have a pack of cards and I spread them out so that the user can pick one. I changed them from Opaque to Transparent so that I change the alpha value (used later in the game).

Anyway, this change means that the cards display differently and Im not sure how to change this. The cards get slight height as they go right to left so that they appear like they do below (first picture). However, when changed to Transparent, they change to the 2nd picture below.

Anyway I thought I could get round this by changing the cards to Transparnet when required, but I cant seem to find out how to access Rendering Mode in script. Also, does anyone have any idea why this is happening?

Thanks
Rob

You’ll want to make two materials, one transparent and one opaque, and use the script to swap between them.

public Material opaqueMat;
public Material transparentMat;
private Renderer rend;

void Awake() {
rend = GetComponent<Renderer>();
}

void UpdateMaterial(bool transparent) {
if (transparent) {
rend.material = transparentMat;
}
else {
rend.material = opaqueMat;
}
}

Then just call UpdateMaterial as needed.

2 Likes

@StarManta I also used this approach until I stumbled into this.

The function, SetupMaterialWithBlendMode, describes what actually happens when you pick different render modes.

Here is a small extension class to help you out.

public static class MaterialExtensions
{
    public static void ToOpaqueMode(this Material material)
    {
        material.SetOverrideTag("RenderType", "");
        material.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.One);
        material.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.Zero);
        material.SetInt("_ZWrite", 1);
        material.DisableKeyword("_ALPHATEST_ON");
        material.DisableKeyword("_ALPHABLEND_ON");
        material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
        material.renderQueue = -1;
    }
   
    public static void ToFadeMode(this Material material)
    {
        material.SetOverrideTag("RenderType", "Transparent");
        material.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.SrcAlpha);
        material.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
        material.SetInt("_ZWrite", 0);
        material.DisableKeyword("_ALPHATEST_ON");
        material.EnableKeyword("_ALPHABLEND_ON");
        material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
        material.renderQueue = (int) UnityEngine.Rendering.RenderQueue.Transparent;
    }
}
25 Likes

Thank you! Works great.

Thank you!

Oh sweet lord thank you. I’ve been on this a week now. AWESOME!

Is there no way to simply “tell” the shader that you want to change blend mode?

1 Like

I won’t pretend to understand all the parameters involved, but that Material Extensions class is very nifty! To those wondering if you can rip just the Override Tag - nope, it would appear all the changes in the class above are necessary.