C# get array with all GameObjects

Hello, is it possible to get array content with all GameObjects from my project?
For example:
I have array

string[] arr1 = new string[] { "Object_Name1", "Object_Name2", "Object_Name3" }

And var

public GameObject myObject;

And i need to check if game objects with names from my arr1 exist in project, if yes then i want save them to my vars. I know how to save it, but i’m not sure how can i get array with all game objects from my project.

I think about this, but maybe you have better idea, if not then ill stay on my idea.

GameObject.Find

Thanks

Something like this maybe?

private GameObject[] Objects = new GameObject[];

for(int i = 0; i < arr1.Length; i++)
{
  if(GameObject.Find(arr1[i]) != null)
  {
      Objects.Add(arr1[i]);
  }
}

This is better:

GameObject[] myObjects;

function Start() {
myObjects = GameObject.FindGameObjectsWithTag("some tag");
}

This array will contain all objects with “some tag” tag.

1 Like
GameObject[] gameObjects = FindObjectsOfType(typeof(GameObject)) as GameObject[];
1 Like
GameObject[] gameObjects = FindObjectsOfType<GameObject>();

I’ve always been curious regarding the difference - Unity’s documentation still shows the way that I’ve done it above. Which is best?

I honestly don’t know. It just seems to take less effort to implement and seems intuitive.

I’m still learning Mono/.NET and I don’t know if its possible to do FindObjectsOfType<typeof(GameObject)>() and if not I can understand the need for both methods to exist so you can find a type at runtime as opposed to having to know the type at compile-time.

Edit: Sorry, I meant FindObjectsOfType<someVariable.GetType()>(), but it doesn’t look like either method of doing so is possible and further justifies the need for having both FindObjectsOfType methods.

Thanks, i will check this in afternoon.