Help fading a canvas image - after changing the image from remote script.

I’m having trouble with displaying a “bonus score” prompt to the user. The prompt is made of two gameobjects - One contains an image and one contains TextMeshPro (the TextMeshPro being a child of the Image object). Each object has a script attached that fades the alpha to 0 from 1 when called.

When calling the fade method from another script I am able to change the image and fade the new image on the first call of this method but subsequent calls only change the image. The TextMeshPro has the exact same setup but does not have this issue. I assume this is because changing the text is not the same as passing a brand new sprite.

Can anyone offer any help?

I’ve tried adding the GetComponent(); to the start of every coroutine in case this part needed refreshing after changing the sprite but it made no difference. I can see the alpa being changed in the code each time the method is called but any new images after the first new image fail to fade.

Fading Code Attached To Image:

Image bonusImage;
private void Start()
{
     //Set alpha to 0 when starting as it contains a dummy image
     bonusImage = GetComponent<Image>();
     Color fadeColor = bonusImage.color;
     fadeColor.a = 0;
     bonusImage.color = fadeColor;
}

public void FadeBonusInfo()
{
      StartCoroutine(FadeImage());
}

IEnumerator FadeImage()
{
      for (float i = 1; i >= 0; i -= Time.deltaTime)
      {
           Color fadeColor = bonusImage.color;
           fadeColor.a = i;
           bonusImage.color = fadeColor;
           yield return null;
      }
}

Change Image And Request Fade Code Attached To Other GameObject:

public Sprite[] awards;
public GameObject bonusScoreImage;
ObjectFade bonusScoreImageScript;

void Start()
{
     bonusScoreImageScript = bonusScoreImage.GetComponent<ObjectFade>();
}
        
private void AwardBonus(int spritToUse)
{
     Sprite theSprite = bonusScoreImage.GetComponent<Image>().sprite = awards[spritToUse];
     bonusScoreImageScript.FadeBonusInfo();
}

Not sure whether this is helpful, but personally I use CanvasGroup for this purpose.

Have a parent GameObject named canvas. Add CanvasGroup component to it.

Have your text and image GameObjects as children of canvas in the scene hierarchy.

Then the following lines can be used as required:.

public CanvasGroup canvas; //assign in Editor

// Make it all visible
canvas.alpha=1;

// Make it all invisible
canvas.alpha=0;

// Stop it from being interactive or clickable
canvas.interactable=false;

// Allow interaction
canvas.interactable=true;

I hope this helps.