Unity как найти объект по компоненту

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Your name

Your email

Suggestion*

Cancel

Switch to Manual

Declaration

public static Object[] FindObjectsOfType(Type type);

Declaration

public static Object[] FindObjectsOfType(Type type,
bool includeInactive);

Declaration

public static T[] FindObjectsOfType(bool includeInactive);

Declaration

public static T[] FindObjectsOfType();

Parameters

type The type of object to find.
includeInactive If true, components attached to inactive GameObjects are also included.

Returns

Object[]
The array of objects found matching the type specified.

Description

Gets a list of all loaded objects of Type type.

This does not return assets (such as meshes, textures or prefabs), or objects with HideFlags.DontSave set.
Objects attached to inactive GameObjects are only included if inactiveObjects is set to true.
Use Resources.FindObjectsOfTypeAll to avoid these limitations.

In Editor, this searches the Scene view by default. If you want to find an object in the Prefab stage, see the StageUtility APIs.

Note: This function is very slow. It is not recommended to use this function every frame.
In most cases you can use the singleton pattern instead.

It is recommended to use Object.FindObjectsByType instead. This replacement allows you to specify whether to sort the resulting array. FindObjectsOfType() always sorts by InstanceID, so calling FindObjectsByType(FindObjectsSortMode.InstanceID) produces identical results. If you specify not to sort the array, the function runs significantly faster, however, the order of the results can change between calls.

Introduction — What we are going to do and why

In this arti­cle we are going to see a method that will allow us to find a COMPONENT of a spe­cif­ic type in Uni­ty from a Script, for exam­ple to find a com­po­nent type AudioSource, Col­lid­er or even a Script that we have cre­at­ed and assigned to a GameOb­ject. The pur­pose of that is to have the ref­er­ence of that com­po­nent inside our Script and to be able to use it accord­ing to our needs. For exam­ple if we want to call a func­tion that is defined in anoth­er Script we are going to need the ref­er­ence of the instance of that oth­er Script to be able to do it.

The method that we are going to see con­sists of using a code instruc­tion that checks each GameOb­ject of the hier­ar­chy and its com­po­nents until it finds the com­po­nent of the type that we indi­cate, if there is a com­po­nent of that type present in the scene the instruc­tion will return it as the exe­cu­tion result and we will be able to store that com­po­nent in a vari­able or to use it imme­di­ate­ly to exe­cute some sim­ple action on the com­po­nent that we found. If on the oth­er hand there is no com­po­nent of that type in any GameOb­ject of the scene, the instruc­tion will return Null and that could lead to an error of type Null­Ref­er­ence­Ex­cep­tion.

In the following video we see how to implement this method to find a component that is unique in the scene

After find­ing that scene com­po­nent we use it to ref­er­ence its GameOb­ject because that is the idea of the video series, but this part is not nec­es­sary, you can use the com­po­nent for what­ev­er you need.

When is this method useful?

  • This method is effec­tive when the com­po­nent we are look­ing for is unique in the scene, if there is more than one com­po­nent of the same type there is no guar­an­tee of find­ing pre­cise­ly the one we are look­ing for.
  • It is rec­om­mend­ed to use this method in some ini­tial­iza­tion func­tion like Awake or Start.
  • It is not rec­om­mend­ed to use this method inside update func­tions like Update because they imply to tra­verse in the worst case the whole hier­ar­chy of the scene. Unless the pro­gram flow is some­how con­trolled so that the instruc­tion is exe­cut­ed only once.
  • If the com­po­nent you want to find is going to be used more than once, it is advis­able to find it once and store it in a glob­al vari­able so that it can be used as many times as necessary.

Detailed procedure of finding a component from the scene through code

Initial conditions

We start from a Script called «Find­Ref­er­ence­O­fAnOb­ject» in which we are going to find the ref­er­ence of a cer­tain GameOb­ject that is in the scene in Uni­ty, inside the Script we will use that ref­er­ence to print its name in con­sole with the instruc­tion of the line 13 of the fig­ure 1.

script to show ways to find gameobjects references in unity scene
Fig. 1: Script we are going to use to see the dif­fer­ent meth­ods to find ref­er­ences of objects from the scene in Unity.

The hier­ar­chy of the scene that we are going to use is com­posed by the GameOb­jects that are shown in fig­ure 2, the object «Script-GameOb­ject» is the one that has the Script in fig­ure 1 assigned and it is the one that will be in charge of find­ing the ref­er­ences, in fig­ure 3 you can see the inspec­tor of this GameOb­ject, where the Script is assigned.

The «GDT (Object to Find)» object seen in fig­ure 2 is the object we want to find from the script, so if we suc­ceed we should see the name of this object print­ed on the console.

Find the reference of a GameObject that has a specific component

If we know that the GameOb­ject we are inter­est­ed in find­ing has a spe­cif­ic com­po­nent assigned to it, such as a «Cam­era», «Rigid­body», «AudioSource» com­po­nent or a script we have cre­at­ed our­selves, we can use that knowl­edge to find the GameOb­ject reference.

I will cre­ate a script called «Some­Script» and assign it to the GameOb­ject we want to find, as shown in fig­ures 4 and 5.

Using the instruc­tion «FindObjectOfType<T>()», where T is the type of object we are look­ing for (in our case it is «Some­Script» type), we can find the ref­er­ence of the «Some­Script» instance that is assigned to that GameOb­ject, then using the dot oper­a­tor we can access the GameOb­ject to which that Script is assigned.

The instruc­tion that does all this can be seen in line 20 of fig­ure 6.

Instruction to find the object reference by type
Fig. 6: Instruc­tion to find the ref­er­ence of the «Some­Script» type object and then get the GameOb­ject to which it is assigned.

When this instruc­tion is exe­cut­ed, Uni­ty will check all the objects in the hier­ar­chy and each one of its com­po­nents until it finds a «Some­Script» type object, when it finds it it returns it as a result, but since we are inter­est­ed in the GameOb­ject to which that Script is assigned, we use the dot oper­a­tor and access the «gameOb­ject» field. If there is no object that has the «Some­Script» com­po­nent assigned to it we will have a null ref­er­ence error because we are using the «object­ToFind» field in line 22 of fig­ure 6.

To keep in mind, if we have more than one GameOb­ject that has assigned the com­po­nent we are look­ing for, Uni­ty will return the first com­po­nent that it finds in its reg­is­ter, in this case ambi­gu­i­ties could arise, we could obtain the ref­er­ence of a dif­fer­ent object to the one we want.

Метод Который находит все объекты с компонентами

Метод Который находит все объекты с компонентами

Мне нужно найти все объекты с компонентом SpriteRenderer какой метод мне в этом поможет?

Orcan
UNITрон
 
Сообщения: 191
Зарегистрирован: 25 сен 2016, 04:22

Re: Метод Который находит все объекты с компонентами

Сообщение waruiyume 12 окт 2017, 20:01

FindObjectsOfType

Аватара пользователя
waruiyume
Адепт
 
Сообщения: 6108
Зарегистрирован: 30 окт 2010, 05:03
Откуда: Ростов на Дону

Re: Метод Который находит все объекты с компонентами

Сообщение Orcan 13 окт 2017, 01:11

спс странно называется я думал это для другого

Orcan
UNITрон
 
Сообщения: 191
Зарегистрирован: 25 сен 2016, 04:22

Re: Метод Который находит все объекты с компонентами

Сообщение Orcan 13 окт 2017, 01:32

Используется csharp

         

public SpriteRenderer[] ZatemnitbObj;

 
void Start ()
{        ZatemnitbObj = GameObject.FindObjectsOfType<SpriteRenderer>();

 
}

Если кто будет искать

Orcan
UNITрон
 
Сообщения: 191
Зарегистрирован: 25 сен 2016, 04:22


Вернуться в Почемучка

Кто сейчас на конференции

Сейчас этот форум просматривают: GoGo.Ru [Bot], Yandex [Bot] и гости: 23



Имеется префаб, на котором висит скрипт с генерацией id для каждого созданного объекта. При запуске сцены генерируется 20 объектов с id (1,2,3…20).
Цель: получить конкретный объект по id (со скрипта). Это нужно для удаления.
Вопрос: можно ли это сделать, если да, то как? C#

задан 27 янв 2017 в 16:50

Вадим Мороз's user avatar

Вадим МорозВадим Мороз

5031 золотой знак7 серебряных знаков22 бронзовых знака

В скрипте иметь словарь, где ключом будет идентификатор, а значением — сгенерированный объект.

Dictionary<int, GameObject> myObjects; 

При инстанциировании складываем туда

var myObj = Instantiate(prefab, new Vector3(2.0f, 0, 0), Quaternion.identity);
myObjects.Add(1, myObj);

Далее когда нужно удалить по id, то обратится к словарю и удалить его оттуда и со сцены.

var objToRemove = myObjects[1];
dic.RemoveAt(1);
Destroy(objToRemove);

Вроде как-то так.

ответ дан 27 янв 2017 в 17:04

Алексей Шиманский's user avatar

Алексей ШиманскийАлексей Шиманский

72.3k11 золотых знаков87 серебряных знаков173 бронзовых знака

Если у тебя есть инстанс скрипта то

instance.gameObject.Destroy();

Так же можешь сделать public static List с твоими обьектами. А внутри обьекта уже иметь айдишник.

Тогда достаточно просто найти в этом листе через Linq обьект с нужным айдишником и его дестройнуть.

Делать же это через какой-то внешний дикшинари — это как-то костыльно, потому не советую. Костылно потому, как хранить параметр обьекта вне обьекта — нелогично с точки зрения ООП.

ответ дан 28 янв 2017 в 17:37

Andrew Stop_RU_war_in_UA's user avatar

1

8 / 8 / 4

Регистрация: 11.03.2015

Сообщений: 212

1

Поиск элементов на сцене

19.02.2016, 16:29. Показов 24220. Ответов 23


Студворк — интернет-сервис помощи студентам

Добрый день. Есть потребность искать элементы на сцене(предполагаю, что лучше по одинаковому компоненту) для последующего сохранения комментария к ним в xml-файле. Возникает вопрос через что и как искать? Нашел возможность поиска по тегу через FindWithTag и с помощью childCount, но не до конца у верен, что это именно то. Так как предполагается, что есть, скажем так, дерево элементов, то есть вложенность. И тут возникает тот самый вопрос: «как искать?». Какие есть возможности и способы?

В заранее спасибо.



0



36 / 11 / 1

Регистрация: 14.09.2015

Сообщений: 60

19.02.2016, 16:38

2

при добавлении элемента записывай его в массив или dict , потом в этом массиве ищеш нужный тебе элемент по параметрам (например по id)



0



8 / 8 / 4

Регистрация: 11.03.2015

Сообщений: 212

19.02.2016, 16:48

 [ТС]

3

Malkkiri, а если элементов конечное число и они в древе, то есть в xml файле нужно будет отразить вложенность и позже вернуть все значения полученные им же. То есть при загрузке программы нужно доставать значения различных элементов и передавать им, а так же в будущем нужно будет редактировать параметры элементов, после чего они должны будут сохраняться в xml файл.

Добавлено через 3 минуты
Так же вопрос. У элемента есть поле(текстовое поле), где хранится текст для всплывающей подсказки. Нужно создать и отдельный скрипт в котором есть данная переменная и навешивать его на объекты сцены или же это можно сделать как-то более умно?



0



751 / 599 / 203

Регистрация: 06.08.2015

Сообщений: 2,432

19.02.2016, 20:18

4



1



8 / 8 / 4

Регистрация: 11.03.2015

Сообщений: 212

22.02.2016, 20:10

 [ТС]

5

Cr0c, спасибо, изучаю.

Добавлено через 1 час 26 минут
Cr0c, но поиск элементов на сцене?.. Как это делать? С помощью чего?

Цитата
Сообщение от Naomis
Посмотреть сообщение

FindWithTag и с помощью childCount

Или я не понял чего? Где это в статье?



0



751 / 599 / 203

Регистрация: 06.08.2015

Сообщений: 2,432

22.02.2016, 22:48

6

Naomis, во-первых, для чего их искать и (во-вторых) почему нельзя при их создании сразу добавить их в список?



0



8 / 8 / 4

Регистрация: 11.03.2015

Сообщений: 212

23.02.2016, 01:27

 [ТС]

7

Cr0c, 1. искать объекты на сцене с параметром (string toolTipText, в этой строковой переменной хранится текст для всплывающей подсказки).

2. Задание такое. Нужно находить элементы на сцене, а так же распознавать их иерархию(древо) и записывать их данные в xml файл, отображая иерархию.



0



751 / 599 / 203

Регистрация: 06.08.2015

Сообщений: 2,432

23.02.2016, 04:50

8

Naomis, реурсивная обработка нужна тогда.



1



HarryCop

1 / 1 / 0

Регистрация: 19.01.2014

Сообщений: 10

23.02.2016, 14:51

9

Поиск по компоненту через

C#
1
твой_класс[] массив = FindObjectsOfType(typeof(твой_класс)) as твой_класс[];

Древо строится рекурсивно через

C#
1
2
3
4
5
6
foreach(твой_класс объект in массив)
{
    //действия над
    объект.transform.parent; //(сначала пробегаем все объекты, у которых нет родителя, потом все объекты у которых родитель - объект_1, потом - объект_2 и т.д.)
    ...
}



1



8 / 8 / 4

Регистрация: 11.03.2015

Сообщений: 212

25.02.2016, 00:21

 [ТС]

10

Cr0c, HarryCop, понял, рекурсивная.

Тогда нужно создать отдельный класс? Посмотрел тут. Что за HingeJoint такой? Что это? Что мне нужно использовать? Какой именно свой класс?



0



1 / 1 / 0

Регистрация: 19.01.2014

Сообщений: 10

25.02.2016, 00:41

11

HingleJoint это один из видов связей между физическими телами (встроенный компонент), взят просто для примера, мол, можно искать объекты по любому компоненту (классу). Если у вас нет своего связующего класса, то можно просто использовать GameObject, так как все объекты на сцене являются его экземплярами.



0



8 / 8 / 4

Регистрация: 11.03.2015

Сообщений: 212

25.02.2016, 01:20

 [ТС]

12

HarryCop, то есть просто используя GameObject и FindObjectsOfType мы записываем всё это в массив GameObject ? Сей час кода попробую наваять. И вопрос на будущее, как в xml это запихнуть? Те самые параыетры string toolTipText?



0



Naomis

8 / 8 / 4

Регистрация: 11.03.2015

Сообщений: 212

26.02.2016, 13:52

 [ТС]

13

HarryCop, компонент задаётся именно в

C#
1
FindObjectsOfType(typeof(GameObject))

Я правильно понимаю? Мне нужно находить обекты с

C#
1
    public string TooltipText = "";

Как мне тогда задать так, чтобы он искал именно их?



0



Cr0c

751 / 599 / 203

Регистрация: 06.08.2015

Сообщений: 2,432

26.02.2016, 14:04

14

Naomis, поле — это не компонент!

C#
1
MyScript[] mss = FindObjectsOfType(typeof(MyScript)) as MyScript[];

И работаете с массивом ссылок на эти экземпляры скрипта.



1



Naomis

8 / 8 / 4

Регистрация: 11.03.2015

Сообщений: 212

26.02.2016, 14:41

 [ТС]

15

Cr0c, А, то есть теперь беру «mss » и пробегаюсь по массиву и ищу там объекты с компонентом «string TooltipText». Я правильно понял? Если да, то работать с элементами массива следует через getComponent? То есть:

C#
1
gameObject.GetComponent <мой скрипт с тултипом>().TooltipText;



0



Cr0c

751 / 599 / 203

Регистрация: 06.08.2015

Сообщений: 2,432

26.02.2016, 15:29

16

Naomis, Вы плохо знаете синтаксис c# ((( У Вас УЖЕ будут прямые ссылки на компоненты класса MyScript.

C#
1
 mss[0].TooltipText = "Damned tooltip";



1



8 / 8 / 4

Регистрация: 11.03.2015

Сообщений: 212

26.02.2016, 15:29

 [ТС]

17

Спасибо. Мне бесконечно стыдно. Если есть, дайте пожалуйста годных мануалов по c# и unity/



0



751 / 599 / 203

Регистрация: 06.08.2015

Сообщений: 2,432

26.02.2016, 15:47

18

Naomis, это же базовые уроки синтаксиса c#, Вам надо азы изучить еще раз, бывает многое не запоминается. По себе знаю



0



8 / 8 / 4

Регистрация: 11.03.2015

Сообщений: 212

26.02.2016, 15:50

 [ТС]

19

Cr0c.Теперь в массиве я ищу элементы этим,

Цитата
Сообщение от Cr0c
Посмотреть сообщение

«Damned tooltip»

я так понимаю, что нужно искать через условие на присутствие или отсутствие этого параметра у элемента. Только немного не представляю как правильно задать условие. С помощью чего проверить присутствие компонента у элемента? Используется тот же «getComponent» или что-то другое? И стоит ли переписать элементы(массив ссылок, если я правильно понял) с имеющимися компонентами в другой, что бы не мешать?



0



751 / 599 / 203

Регистрация: 06.08.2015

Сообщений: 2,432

26.02.2016, 15:55

20

Naomis, а Вы разве не создали единый скрипт для подобной информации? Можно же более одного скрипта на го кидать.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

26.02.2016, 15:55

20

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Просело пластиковое окно как исправить
  • Как найти печку в minecraft
  • Яблоня растет криво как исправить
  • Boot на приставке как исправить
  • Как найти детские палатки

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии