Listing and updating objects and their distances in a 2D, top-down space sim.

I am developing a top-down, 2d space sim in which I would like the player to see a list of planets, ships, etc. in which they are in close proximity to as well as their distances. I would like this list to be kept up to date and sorted from closest objects to farthest. This should be familiar to anyone who has played space sims such as Eve Online.

The way I am currently doing this, is by running through a loop of all gameobjects I want to see on the list and building a column (list) of gameobjects that contain text components showing their name and distance from the player ship. This is done at the beginning of each frame, and then they are deleted at the end of the frame thus keeping the list up to date. However, deleting and instantiating all the game objects each frame to form this list doesn’t run well. Here is my code:

void Update()
    {
        // DELETE OLD LIST 
        for (int i = contentGO.transform.childCount - 1; i >= 0; i--)
        {
            GameObject childObject = contentGO.transform.GetChild(i).gameObject;
            Destroy(childObject);

        }


        for (int i = 0; i < entries.Length; i++)
        {
            if (entries[i] != null)
            {
                GameObject newGO = Instantiate(entryNameGO);
                newGO.transform.SetParent(contentGO.transform);

                int locY = -10 - (i * 10);
                newGO.transform.localPosition = new Vector2(0, locY);

                newGO.GetComponent<TextMeshProUGUI>().text = "Name: " + pois[i].gameObject.name;
            }

        }
    }

Thank you for any help.
John Powell

Can’t you just move them instead of deleting them? Or use an Object Pool at the very least.

I’m thinking I might just make a bunch of blank entries in the editor and change their text values using C# as objects get closer and further away. However, I’m worried this will interfere with how the list scrolls. I don’t want the user to have to scroll blank entries. Maybe enabling and disabling the blank text objects when they aren’t needed?

1 Like

Instead of destorying them I would just set them inactive. Then loop over your entries and for each entry activate one gameobject and set the position and name. In case you are running out of gameobjects just instantiate a new one. So in the first frame you have 0 gameobjects but 3 entries → instantiate 3 gameobjects. Next frame deactivate 3 and you have 4 entries so the first 3 activate the gameobjects and the 4th instantiate a new one. Next frame you have 4 gameobjects but only 2 entries, so 2 gameobjects are populated and the gameobject 3 and 4 just stay active until they are needed in a future frame.