How to put gameObjects into the list?

24,342

Solution 1

I found the solution for my question, thereby I'll ask my question, maybe it will be helpful for someone else:

 unityGameObjects.Add(GameObject.Find(unityObject.Value));

Solution 2

You first create your list.

List<GameObject> unityGameObjects = new List<GameObject>();

You need to have a reference to the GameObject you which to add to the list. You can do this by looking for the GameObject or by creating a new instances of it.

Looking for the GameObject

GameObject g = GameObject.Find("NameOfGameObject");
unityGameObjects.Add(g);

Creating a new instance

You can't call new on GameObjects because they are MonoBehaviours but you can instantiate them from a prefab.

GameObject g = Instantiate(prefab);
unityGameObjects.Add(g);

Solution 3

MyList.AddRange( new List<GameObject> { new GameObject { name = "Frank", tag = "3" ,layer= 2, active = isActiveAndEnabled, hideFlags =  HideFlags.HideInHierarchy, isStatic = false },
                                       new GameObject { name = "Jill", tag = "3" },
                                       new GameObject { name = "Dave", tag = "5" },
                                       new GameObject { name = "Jack", tag = "8" },
                                       new GameObject { name = "Judith", tag = "12" },
                                       new GameObject { name = "Robert", tag = "14" },
                                       new GameObject { name = "Adam", tag = "1" } } );

Solution 4

unityGameObjects.Add(new GameObject());
Share:
24,342
Timy Ash
Author by

Timy Ash

Updated on August 19, 2020

Comments

  • Timy Ash
    Timy Ash over 3 years

    I have gameObjects and I need to put them to the list, something like that:

    List<GameObject> unityGameObjects = new List<GameObject>();

  • Timy Ash
    Timy Ash over 11 years
    its an adding gameobject to the list, in my case I need to instanciate the unityGameObjects list in another script, it will be helpful if you'll help in this case
  • apxcode
    apxcode over 9 years
    This answer is wrong and does not solve the problem.
  • AdrianHHH
    AdrianHHH over 4 years
    Welcome to Stack Overflow and thank you for answering the question. However, please make the effort to format your code nicely (I have done that for you here). After entering your answer it is easy to used the edit link beneath the answer to alter the format or content.