Alessandro
Alessandro

Reputation: 123

How to change alpha of a Shader in Unity by code

I have a GameObject with a material set to transparent, and I want to change its alpha to 80 instead of 255. But I want to do it by code, not with the editor sliders. Is there a simple way to change the alpha of a shader using just a line of code? Something like:

MyObject.GetComponent<Material>().shader.alpha = 80;

I've looked around the internet and I've found only more complex solutions...

Upvotes: 1

Views: 8190

Answers (1)

Menyus777
Menyus777

Reputation: 7007

I think this should do the trick:

public class SetAlpha : MonoBehaviour
{
    public Material materialWithAlphaValue;

    public void ChangeAlphaValue(Color color)
    {
        materialWithAlphaValue.SetColor("_MY_COLOR_SHADER_VARIABLE_NAME", color);
    }
}

UPDATE:

public class SetAlpha : MonoBehaviour
{
    public Material materialWithAlphaValue;

    public void ChangeAlphaValue(float alpha)
    {
        var color = materialWithAlphaValue.GetColor("_MY_COLOR_SHADER_VARIABLE_NAME");
        materialWithAlphaValue.SetColor("_MY_COLOR_SHADER_VARIABLE_NAME", new Color(color.r, color.g, color.b, alpha));
    }
}

UPDATE 2:

Using Material.Color is the same as using Material.GetColor("_Color"); this is the default naming for base colors in the standard unity shaders.

public void ChangeDefaultMatAlpha(float a)
{
    _MyMaterial.color = new Color(_MyMaterial.color.r, _MyMaterial.color.g _MyMaterial.color.b,
        a);
}

Upvotes: 2

Related Questions