- Home /
 
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
Answer by _joe_ · Mar 31, 2015 at 05:22 PM
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.
Thank you for marking the question as "Answered" if this helped :)
Thank you so much, your a life saver I have to show of a demo of the game tomorrow in front of the whole college. I have been looking around all day trying to figure out how to do this by doing things like, Renderer.enabled = true or false, making it a public variable and using a different script on the HUD I cant believe it was that easy. Thank you
Your answer