How do you get sprite to appear on HUD when collected

I’m coding a 2D platformer in c#. I have a key and when collected i want the picture of the sprite to appear in the top right of the screen showing the player that they have collected the item.This is the code I have so far

using UnityEngine;
using System.Collections;

public class KeyScript : MonoBehaviour {

bool hasKey = false;


void OnTriggerEnter2D(Collider2D other)
{
	if(other.gameObject.tag == "Key")
	{
		Destroy(other.gameObject);
		hasKey = true;
        
	}
}	

}

"
I think you would put a line under “hasKey = true;” but im not sure what the right words to use for this are. I was wondering if i attach a picture of the key to my HUD but turn the sprite renderer off if their was a line i could put in to turn it back on when the key is collected or if there is a different way to solve my problem. Many thanks

It’s very simple.

Start by adding the Sprite to your HUD (the Key Sprite), scale it, position and rotate it the way you want till you’re happy with it (Don’t forget to anchor it accordingly too).
Then turn it off (Untick the GameObject).

Now in your Trigger function:

//Reference variable to your Key sprite
public GameObject myKey;

void OnTriggerEnter2D(Collider2D other)
 {
     if(other.gameObject.tag == "Key")
     {
         Destroy(other.gameObject);
         hasKey = true;
         
         //Code to add
         myKey.SetActive(true);
     }
 }    

That’s about it, you can do it dynamically (instantiate the UI icon whenever you want and add it to the UI canvas), but for a key Icon, i believe this is the fasted/best approach.