1

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.

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Tanks! After sucessfully cahnging that line things are working out. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.