Better solution for GameObject.FindGameObjectsWithTag

Hi,

In my game all the time people walk around, get destroyed and get created.
Every 5-10 seconds I need to take a random gameobject and make him do something. But what is the best way to choose a random gameobject. I can use GameObject.FindGameObjectsWithTag but I hope their is a more performance friendly solution.

What I have a.t.m. is the following:

GameObject[] ArrayEnterPeople = GameObject.FindGameObjectsWithTag("People");
int RandomNumb = Random.Range(0,ArrayEnterPeople.Length);
GameObject EnterPeople = ArrayEnterPeople[RandomNumb];

Could someone please help me with my problem?

I usually create custom spawners, which automatically add things to pool.
Here’s a basic example.

using UnityEngine;
using System.Collections.Generic;

public class MyClass : MonoBehaviour {

public static MyClass Singleton;
private readonly List<GameObject> _elements = new List<GameObject>();

private void Awake(){
    Singleton = this;
}

public GameObject Person(GameObject prefab, Vector3 position){
    GameObject value = (GameObject)Instantiate(prefab, position, Quaternion.identity);
    _elements.Add(value);
    return value;
}

public GameObject getRandomPerson(){
    return _elements[Random.Range(0, elements.Count)];
}

}

Technically, there no need need to inherit from monobehaviour, and script does not need to exist in scene (right now it has to be on gameobject in scene). Just remember to clean up the elements on level load.

To call, simply:

GameObject spawnedPerson = MyClass.Singleton.Person(prefab, position);

and

GameObject value = MyClass.Singleton.getRandomPerson();

You can have a generic list of people. Every time someone is created, add them to the list, and take them off the list when they are destroyed. However, you talked about performance; creating/destroying isn’t efficient, I’d recommend an object pool instead.