How do i programmatically change an image alpha

I’ve been stuck on this one now for about two hours, as I haven’t used Unity since 5.x.

What I think I want to do, is have the alpha of the UI image set to 0 on Awake() and then have it toggle between 0 and 255 when the player enters and exits the screen space occupied by the button. For the life of me though, I just can’t seem to get it to work and my brain is pretty fried from the frustration.

I’m sure that when it finally works, I’ll be amazed at how simple of a thing I’d missed, but until then, any help would be great.

using UnityEngine;
using UnityEngine.EventSystems;

public class Direction : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    public UnityEngine.UI.Image button;
    public Color color = Color.white;

    private void Awake()
    {
        button.color = color;
        color.a = 0f;
    }
    
    public void OnPointerEnter(PointerEventData eventData)
    {
        color.a = 1f;
        Debug.Log("Hover");
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        color.a = 0f;
        Debug.Log("exit");
    }
}

Changing the “Color” struct doesn’t change the color applied to the Button.

Thats because how “struct” works - not a reference, but a value type. You should definitley check out a video/documentation about the differences.

So what you have to do is, first set the color.a = 0f; and then set the button.color = coior;

Change the color variable itself and then asigning it to the button will help you out.

Again; check out the difference between structs and classes - very important.