Asign prefab to game object based on tag

Hi there,
I have three empty GameObjects.

public GameObject animals;
and 10 different animal prefabs.
I want from a Random animal prefab Spawner OnTriggerEnter2D to assign these three GameObject a prefab based on prefab tag

Hi OM3TRIX, there are several ways to go about this and conceptually they are all similar:

  1. you create collection - an array, list, or dictionary - of all the prefabs at the start of the game

  2. you create an collection - an array, list, or dictionary - the tags at the start of the game

  3. you associate the two collections by element index or key (in the case of dictionary)

  4. when you want to instantiate a specific game object, you use the tag collection to index or key to get the respective prefab in the prefab collection.

if it were me, I would use a dictionary because it handles both tag and prefab in one collection:

for example, in pseudo code:

// declare the collection
Dictionary<string, GameObject>  prefabDictionary = new Dictionary<string, GameObject>;
    
 // assumes catPrefab and dogPrefab are references to the prefab objects
// load up the collection, for each prefab you'll repeat this, for example:
prefabDictionary.Add( "cat", catPrefab );
prefabDictionary.Add( "dog", dogPrefab );
   
// then, for example, to get an element to instantiate, in your example
animals[0] = (GameObject) Instantiate( prefabDictionary["cat"] );
animals[1] = (GameObject) Instantiate( prefabDictionary["dog"] );
   
// or, for example, assuming there is a key "horse" in the dictionary
string aTag = "horse"
animals[1] = (GameObject) Instantiate( prefabDictionary[aTag] );