Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Remove New Game Object after it is "used"

Discussion in '2D' started by Alv1s, Jul 3, 2015.

  1. Alv1s

    Alv1s

    Joined:
    Jul 9, 2014
    Posts:
    2
    Hello,

    sorry if this is "stupid" question, but it's been bothering me for a while :) I'm creating very simple " Guess the country flag " game on android for my kids ( will share it in the future for free to anybody ). Idea is very simple:
    1. Two country flags appear, one is correct and another is not correct
    2. 1 label with "correct" country name appears on top
    3. Kid reads the country name and press on correct flag
    4. Points for correct guess are added.
    5. New flags are being displayed , and game goes on.
    Please dont take into mind "graphic" yet :)
    upload_2015-7-3_11-16-45.png
    I've created sprite atlas sheet with 220 flags and they are randomly added to the screen, position of correct flag is also changing randomly, and everything is fine.
    My issue ( or maybe this is not an issue at all ) is that "New Game Object" is created for each new flag
    upload_2015-7-3_11-19-29.png
    , and amount of objects is growing very fast, maybe it can consume too much memory after 1000 new objects, I dont know :)
    I noticed that each of this New Game Object is storing sprites of previous flags that were on screen.
    So what is correct way to remove ( destroy? ) gameObject that is not "needed" anymore?
    I tried Destroy(gameObject) but it destroys everything and no flags are being displayed.
    I tried to use object.Instantiat no luck either..
    Logic of my code:
    void Awake(){Empty}
    void Start (){ loading sprites, calling draw_flags () }
    void draw_flags(){ gameObject flag 1 = new GameObject(); , GameObject flag2=.... , flags drawing }
    void Update(){ checks colliding , moves flags out of screen ( chaning position, I would like to remove objects here ), calls draw_flags}
    void OnGUI { labels and score }
    Thanks in advance
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    You remove unwanted GameObjects with Destroy(). If you call Destroy(gameObject), it will remove the current Game Object, that is the Game Object to which the script is attached. If I understand you correctly, you want to remove the Game Object named flag1. Which should be done like this; Destroy(flag1).