Cannot set UnityUI.Image opacity when place on a UnityUI.Button


I have two buttons, say A and B for arguments sake. Both UnityUI.Buttons contain a UnityUI.Image. For button A, the image colour is set to 1f alpha. For button B, the contained image is set to 0.4f alpha, making it seem dim due to the transparency.

When I click A, I want to reverse the opacity and have A’s image with 0.4f alpha, and B’s image with 1f alpha.

I have written this code that seems correct:

public static void SetOpacity(UnityEngine.UI.Image btn, bool enable)
    // Full opacity on the alpha if enabled.
    if (enable)
      btn.color = new Color(btn.color.r, btn.color.g, btn.color.b, 1f);
      btn.color = new Color(btn.color.r, btn.color.g, btn.color.g, 0.4f);

I keep the RGB the same as it originally was for the new colour as I don’t need anything but the opacity to change.

I have hooked up click events for both buttons to invoke this code. Which it does as the debug.log is logging! But I cannot see any change in the opacity within the UI. What am I doing wrong? I tried this solution as well, the image doesn’t have a “colors” property.

The attached screen shot shows the button in question, with the image child. You can see the value of the alpha in the image starts at 0.4f for the stop button.

Thanks in advance!

noticed that you have put the button’s Image in a child rather than at the same object with the button component. is there any reason for this? We cannot judge if this is due to the button’s animator (probably not) as we cannot see the button component, please post that here also.

If you really only want to change alpha you may also try to use a canvas group component on your button object (the parent), then you can change all the children’s alpha at the same time via script or animation

Putting the image as a child of the button meant I could still take advantage of hover states and click of the button when over the top of the image (if the image is at the same level as the button this isn’t the case).

It is effected by the transition component of the button, when I set this to None, the opacity code I wrote works, only snag is that I lose the button transitions for disabled, hover etc, which I am using.