Best practices to select a group of gameObjects
I'm new to Unity and I need to select a group of gameObjects.. right now I found 2 options:
1) Assigning a tag and selecting objects by tag (bad for some cases as I can't assign multiple tags to objects)
2) Assigning objects as children of a gameObject, selecting the parent gameObject and iterating through the children with transform.
Which would you recommend? Or perhaps a third option?
Answer by UnityCoach · Jan 12, 2017 at 01:08 PM
You can add to them a component that stores all instances in a static List.
Like :
using System.Collections.Generic;
public class GameObjectCollector : MonoBehaviour
{
public static List <GameObject> collection;
void Awake ()
{
collection.Add (gameObject);
}
}
You can even go further and add a list of custom tags and store everything in a dictionary :
public class GameObjectCollector : $$anonymous$$onoBehaviour
{
public static Dictionary<string, List<GameObject>> collections;
public string tags;
void Awake ()
{
if (collections == null)
collections = new Dictionary<string, List<GameObject>>();
string [] tagsArray = tags.Split(';');
foreach (string t in tagsArray)
{
if (!collections.Contains$$anonymous$$ey(t))
collections.Add(t, new List<GameObject>());
collections[t].Add(gameObject);
}
}
}
Of course, you then want to handle the destruction of objects :
void OnDestroy ()
{
string [] tagsArray = tags.Split(';');
foreach (string t in tagsArray)
{
collections[t].Remove(gameObject);
}
}
Your answer
Follow this Question
Related Questions
How to toggle elements within a prefab in Unity 0 Answers
Unity5/C# beginner here! Need some scripting help :) <3 1 Answer
Adjust the size of the object within a parent container 0 Answers
Loot table problems 1 Answer
Game crashes on iPhone 11 0 Answers