Home > Back-end >  Get all gameobjects that begin with a certain string
Get all gameobjects that begin with a certain string

Time:02-12

I am trying to collect all gameObjects that begin with certain string or a tag. For example, the string/tag is "Sub-". I would like to add all of them to my list. How do I achieve this?

public List<GameObject> subs = new List<GameObject>();

private void Start(){
   foreach(GameObject subGroup in GameObject.FindGameObjectsWithTag("Sub-")) {
 
             subs.Add(subGroup);
         }
 }

CodePudding user response:

using Linq you could do something like e.g.

using System.Linq;

...

// get all Transform components of the scene
// pass in true to include inactive ones
var all = FindObjectsOfType<Transform>(true);

// Filter and only keep the ones whee the name starts with your string
subs = all.Where(obj => obj.name.StartsWith(nameOfObj)).ToList();
// Or use a certain tag
subs = all.Where(obj => obj.CompareTag(nameOfObj)).ToList();
// or check if the tag starts with your string
subs = all.Where(obj => obj.tag.StartsWith(nameOfObj)).ToList();

see Object.FindObjectsOfType and Linq Where

  • Related