How to add GameObjects to a list? Please respond.

Can someone please help me with this code?

I am trying to add all the GameObjects I have instantiated in my scene to a list I have created.
The list contains a new Class called noOfGameObjects which I am hoping will also tell you the GameObject position.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NumberOfGameObjects : MonoBehaviour {

    private GameObject[] gameObjects;
    public List<noOfGameObjects> objects = new List<noOfGameObjects>();
   

    // Use this for initialization
    void Start () {
       
    }
   
    // Update is called once per frame
    void Update () {
        gameObjects = GameObject.FindGameObjectsWithTag("Objects");
      
       
      //  add these GameObjects to the list of noOfGameObjects
    }


}
[System.Serializable]
public class noOfGameObjects
{
    public GameObject gameObject;
    public Vector3 position;

   
   
}

Can someone please tell me how to add the array of GameObjects to the list of noOfGameObjects?

Thanks

list = array.ToList();

Why use this extra class when ‘position’ is gameObject.transform.position?

If you must, loop over the array with a for loop and use the index to modify the class variables on the same index.

I would NOT iterate over ALL GameObjects EVERY frame. Just make your own methods for spawning (Instantiate) and despawning (Destroy) and use them all over your project. These methods can add and remove the GameObjects to/from the list and call Instantiate/Destroy. I use this method to have a List of objects for each Gamestate and can enable/disable them when I change state.

Because I want the position displayed under array of noOfGameObjects.

Can you explain to me how to loop over the array? Thanks.

This is extremely basic stuff.

https://www.dotnetperls.com/for

the objects are already instantiated in another script which I don’t want to mess around with.

I just want this script to show me a list of GameObjects that have been instantiated with their positions.

You could convert it to a list, however since you’re just iterating there is no need. But, to answer your question, this should work:

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class NumberOfGameObjects : MonoBehaviour
{
    public List<GameObject> objects;
 
    // Use this for initialization
    void Start () {
     
    }
 
    // Update is called once per frame
    void Update () {
        objects = GameObject.FindGameObjectsWithTag("Objects").ToList(); // This is very bad for performance. Rather, try to keep track of when 'Objects' are created and destroyed, then add / remove them from the list
    }
}
for (int i = 0; i < gameObjects.Length; i++)
        {
             ////what do I do here to get it into the noOfGameObjects list?
        }

Yes but I also want the positions displayed as well.

Also if 50 GameObjects have been instantiated, I want to destroy the gameObjects that get past the number of 50…if that makes sense?

 // You use google to learn the basics

https://www.dotnetperls.com/list

That’s pretty simple stuff. This is basic programming. Creating objects and adding to a list. Unity even has it’s own guide https://unity3d.com/learn/tutorials/modules/intermediate/scripting/lists-and-dictionaries

However, as mentioned, you probably don’t need to do this every frame. Even if you need to do it once to add existing objects, after that you should have methods to remove, add, update, etc from the list. You can easily either check the list for size before you instantiate (thus avoiding creating and destroying right away) or if you really wanted, instantiate and check the list size and then destroy the newly created object.

yes I know it is simple to you but what I am actually trying to do is pass the array of GameObjects to another class.
This other class has the position of the GameObject.

Does that make sense?

Also the reason why I am creating this script, is that when the list reaches 50 gameObjects. All other GameObjects after the number of 50 will be destroyed.

I am procedurally generating objects on a terrain, however it is very taxing on the computer when too many objects are instantiated. So I want to destroy some of the gameObjects when it gets past 50 game objects. So that there will only be 50 game objects at all times maximum. I need the position, so when the game objects are re-instantiated it will place them back in the same position. But that’s not what I am worried about now…

All I want to know is how to pass the array of GameObjects into the other class that I am using for a list? That’s all I want to know.

I am fairly intermediate with C sharp, I don’t know much about lists and loops yet though, I am still learning that process. It would help me out a lot if someone could just give me an idea on how to do it. You would save me a lot of time.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NumberOfGameObjects : MonoBehaviour {

    private GameObject[] gameObjects;
    public List<noOfGameObjects> objects = new List<noOfGameObjects>();
 

    // Use this for initialization
    void Start () {
     
    }
 
    // Update is called once per frame
    void Update () {
        gameObjects = GameObject.FindGameObjectsWithTag("Objects");
    
        for (int i = 0; i < gameObjects.Length; i++)
        {
            //  add these GameObjects to the list of noOfGameObjects
        }


    }


}

////I want to pass all the GameObjects to this list below:

[System.Serializable]
public class noOfGameObjects
{

    public GameObject gameObject;
    public Vector3 position;

 
 
}

Okay, I will solve your problem. However I must stress that there are many things wrong with this approach, some of which others have pointed out.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NumberOfGameObjects : MonoBehaviour
{

    private GameObject[] gameObjects;
    public List<noOfGameObjects> objects = new List<noOfGameObjects>();


    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        gameObjects = GameObject.FindGameObjectsWithTag("Objects");
        objects.Clear();
        for (int i = 0; i < gameObjects.Length; i++)
        {
            //  add these GameObjects to the list of noOfGameObjects
            var obj = new noOfGameObjects()
            {
                gameObject = gameObjects[i],
                position = gameObjects[i].transform.position
            };
            objects.Add(obj);
        }
    }
}

////I want to pass all the GameObjects to this list below:

[System.Serializable]
public class noOfGameObjects
{
    public GameObject gameObject;
    public Vector3 position;
}

Class noOfGameObjects is not a List. It’s a class with one GameObject variable and a fairly useless Vector3 variable.

To populate a List you do exactly what the two links I posted tell you to do. It’s explained very clearly and we don’t need to repeat the information. Read the tutorials. Use a for loop to access the content and assign it as you see fit.

This is not intermediate, this is very basic stuff. For loops are among the first things you learn.

I’m going to add my 2 cents here, intended as helpful:

If you do not know lists, arrays, and loops, you should truly consider taking some time to learn that and any other basic functionality of programming. You will use these things every day you program (or near enough), and you will be very thankful that you understand them. :slight_smile:

1 Like

Thank you so much!

I knew it was something simple…I am mostly an artist doing Zbrush work. And I have fairly basic knowledge of C# but I learned a lot for you.

I will have to update my knowledge of C sharp, it has been a while since I last coded.

Ok so it seems that the script works however, it is creating new lists constantly…when I only want it to get the list of objects in the scene?

Which basically freezes the entire Unity editor.

It was mentioned several times to not do this in the Update() method.

So should I use a Coroutine instead?

I know it was mentioned but I just wanted to see what would happen. I probably should have just experimented myself.

Running this repeatedly in a Coroutine isn’t going to fix the issue. All of the “Find” commands are extremely taxing, and should be used sparingly. You should never use any of them in every update, (no matter if in the Update method or every update inside a Coroutine). A Coroutine doesn’t magically make something that is very slow go any faster.

The recommended use for any of the “Find” commands is to never use them, because they really are that bad, and get your references using some other method. For example, whenever you instantiate one of your objects that is the point you add it to the list. Whenever you destroy an object, you go and remove it from your list. Then you never need to use a Find method.

If you do use a Find command, you use them very sparingly, such as calling them when setting up references for an object in its Awake or Start method. What you don’t do is design your game so you need to use them 60+ times per second. You can’t make that perform well. Figure out another way to do this.