Home c# Unity FindGameObjectsWithTag

Unity FindGameObjectsWithTag

Author

Date

Category

What algorithm is it looking for? When there are 15 objects in the scene, it returns an array with them. If you repeat, it returns in the same sequence. If you swap objects on the scene, the sequence is the same. Rename objects – the same.

The question is – how to make this method look for objects exactly in a given sequence? Those. let’s say he would put this object first, this one second ..


Answer 1, authority 100%

using System.Collection.Generic;
using System.Linq;
using UnityEngine;
public class YourFindClass: MonoBehaviour
{
  void Find () {
    GameObject [] array = GameObject.FindGameObjectsWithTag ("yourTag");
    List & lt; GameObject & gt; list = new List & lt; GameObject & gt; (array);
    list = list.OrderBy (value = & gt; value.GetComponent & lt; yourIDScript & gt; (). id) .Reverse (). ToList ();
    //or
    list = list.OrderBy (value = & gt; value.name) .ToList (); // sort by object name
  }
}

as a result, get the GameObject sheet from largest to smallest by ID. you can run over the sheet and “pull out” the necessary objects from it.
Any use of Dictionary

void Find () {
   GameObject [] array = GameObject.FindGameObjectsWithTag ("help");
   List & lt; GameObject & gt; list = new List & lt; GameObject & gt; (array);
   list = list.OrderBy (value = & gt; value.GetComponent & lt; yourScript & gt; (). id) .Reverse (). ToList ();
   Dictionary & lt; string, GameObject & gt; lists = new Dictionary & lt; int, GameObject & gt; ();
   foreach (yourScript item in list) {
     lists.Add (item.id, item.gameObject);
   }
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions