0

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

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

apxcode
  • 7,696
  • 7
  • 30
  • 41
Timy Ash
  • 107
  • 1
  • 1
  • 11

4 Answers4

5

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);
apxcode
  • 7,696
  • 7
  • 30
  • 41
1
unityGameObjects.Add(new GameObject());
apxcode
  • 7,696
  • 7
  • 30
  • 41
  • 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 – Timy Ash Nov 22 '12 at 09:55
  • This answer is wrong and does not solve the problem. – apxcode Oct 11 '14 at 23:47
1
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" } } );
AdrianHHH
  • 13,492
  • 16
  • 50
  • 87
ALBERT
  • 11
  • 2
  • 1
    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. – AdrianHHH Aug 18 '19 at 18:03
0

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));
Martin
  • 22,212
  • 11
  • 70
  • 132
Timy Ash
  • 107
  • 1
  • 1
  • 11