- Home /
How do I destroy a Instantiated UI image that is pushed on the Canvas?
Hello,
Was hoping someone can help me. I'm creating a game and i'm stuck at this part as this part and I assume I'm missing something. I'm creating a sorting game recycle, garbage, paper, and compost items. These random items appear in a sequence of 10. The code picks between 12 prefabs randomly and then drops them through the scene. I've created another code for the prefab to Instantiate a UI quip as seen here:  Now the problem is I can't destroy it. This image populates in the canvas and my head can't get around to accessing it and destroying. The code for Instantiating the ItemUI Image:
 Now the problem is I can't destroy it. This image populates in the canvas and my head can't get around to accessing it and destroying. The code for Instantiating the ItemUI Image:  public class S_TomatoUI : MonoBehaviour { public GameObject uiObject; public float positionOffset; protected Image uiImage; // Start is called before the first frame update void Start() { uiImage = Instantiate(uiObject, FindObjectOfType<Canvas>().transform).GetComponent<Image>(); uiImage.transform.SetAsFirstSibling(); } // Update is called once per frame void Update() { uiImage.transform.position = Camera.main.WorldToScreenPoint(transform.position + Vector3.up * positionOffset); } public void OnDestroy() { Destroy(uiImage.gameObject); } }
Can someone please help me.
Thanks,
Answer by Spip5 · Aug 13, 2020 at 01:00 AM
 public class S_TomatoUI : MonoBehaviour { 
 public GameObject uiObject; 
 public float positionOffset; 
 
 private Image uiImage; 
 private GameObject UIElement;
 
 // Start is called before the first frame update 
 void Start() 
 {
 UIElement = Instantiate(uiObject, FindObjectOfType<Canvas>().transform);
 uiImage = UIElement.GetComponent<Image>();
 uiImage.transform.SetAsFirstSibling();
 
 } // Update is called once per frame 
 void Update() 
 {
 UIElement.transform.position = Camera.main.WorldToScreenPoint(transform.position + Vector3.up * positionOffset);
 }
 
 public void onDestroy()
 {
 Destroy(UIElement.gameObject);
 }
 }
Your answer
 
 
             Follow this Question
Related Questions
Trouble with destroying an instantiated prefab 2 Answers
i need to destroy prefab clones 1 Answer
Destroying a instantiated prefab? 2 Answers
Destorying prefab and instanstiating again? 0 Answers
My prefab isn't getting destroyed 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                