strum
strum

Reputation: 13

How to get GameObjects with different tags in the same Array | Unity3D

I have 2 GameObjects: 1.) Screws (with 2 empty child objects with attached script to spawn different prefab types of screws) 2.) Plate

To the Plate Object, I have a script assigned which gets specific tags and puts these objects with that tag into an array. However, I added a method to get 2 different types of tags put into a list and after that into one array (Screws) as seen below.

The instantiation of the screws happens inside another scripts Awake() method. Both kind of screws are spawned x20 so there are 40 in total.

Trying to get all Objects with one tag is working fine.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class ScrewHandler : MonoBehaviour
{
    /*------------- Declaration of vars etc. -------------*/

    public GameObject[] Screws;

    /*----------------- Create Array --------------------------*/
    private void Start()
    {
        Debug.Log("Start called");

        Screws = FindGameObjectsWithTags(new string[] {"ScrewA","ScrewB"});

        // custom method to get multiple types of tags into one array
        GameObject[] FindGameObjectsWithTags(params string[] tags)
        {
            var all = new List<GameObject>();

            foreach(string tag in tags)
            {
                var temp = GameObject.FindGameObjectsWithTag(tag).ToList();
            }
            return all.ToArray();
        }

    }

}

IF things are working out, I should be able to see the Array with all the Objects in the inspector of the script.

Upvotes: 1

Views: 1862

Answers (1)

Malphegal
Malphegal

Reputation: 270

Your custom FindGameObjectsWithTags method will return an empty array each time you will run it.

The thing is, you just never add any element to the variable all, so converted to an array will result to an empty array as well.

I will suggest you to do as the following :

GameObject[] FindGameObjectsWithTags(params string[] tags)
{
    var all = new List<GameObject>();

    foreach (string tag in tags)
    {
        all.AddRange(GameObject.FindGameObjectsWithTag(tag).ToList());
    }

    return all.ToArray();
}

EDITED : Typo

Upvotes: 1

Related Questions