1

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...

3
  • Look for sharedMaterial and Material Property Blocks, they help you changing the attributes of your material, which will reflect in the shader. Commented Sep 5, 2019 at 16:01
  • @Daniel I wrote MyObject.GetComponent<Renderer>().sharedMaterial.SetFloat("color.a", 0.4f); But I think I can only set a color or a float property, and the alpha is neither of those things, right? How do you think I can change it? Commented Sep 5, 2019 at 17:31
  • 1
    Alpha is a float between 0 and 1. If you are having problems with setting the alpha, you must remember to set the tags (Tags {"Queue"="Transparent" "RenderType"="Transparent" }) and to set the correct blend type (Blend SrcAlpha OneMinusSrcAlpha), otherwise your alpha won't make a difference. Commented Sep 6, 2019 at 2:16

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! But you propose to assign a new color, instead of changing just the alpha of the existing one, right?
@Alessandro Yes! Thats what i did, but you can copy the original r,g,b values then assign a custom a value, i think there is a method called GetColor() :)
thank you, that last one works fine! But I had to change the color option from RGB 0-255 to RGB 0-1, otherwise it had a strange effect, like infrared vision... Weird! :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.