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 article we are going to see a method that will allow us to find a COMPONENT of a specific type in Unity from a Script, for example to find a component type AudioSource, Collider or even a Script that we have created and assigned to a GameObject. The purpose of that is to have the reference of that component inside our Script and to be able to use it according to our needs. For example if we want to call a function that is defined in another Script we are going to need the reference of the instance of that other Script to be able to do it.
The method that we are going to see consists of using a code instruction that checks each GameObject of the hierarchy and its components until it finds the component of the type that we indicate, if there is a component of that type present in the scene the instruction will return it as the execution result and we will be able to store that component in a variable or to use it immediately to execute some simple action on the component that we found. If on the other hand there is no component of that type in any GameObject of the scene, the instruction will return Null and that could lead to an error of type NullReferenceException.
In the following video we see how to implement this method to find a component that is unique in the scene
After finding that scene component we use it to reference its GameObject because that is the idea of the video series, but this part is not necessary, you can use the component for whatever you need.
When is this method useful?
- This method is effective when the component we are looking for is unique in the scene, if there is more than one component of the same type there is no guarantee of finding precisely the one we are looking for.
- It is recommended to use this method in some initialization function like Awake or Start.
- It is not recommended to use this method inside update functions like Update because they imply to traverse in the worst case the whole hierarchy of the scene. Unless the program flow is somehow controlled so that the instruction is executed only once.
- If the component you want to find is going to be used more than once, it is advisable to find it once and store it in a global variable 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 «FindReferenceOfAnObject» in which we are going to find the reference of a certain GameObject that is in the scene in Unity, inside the Script we will use that reference to print its name in console with the instruction of the line 13 of the figure 1.
The hierarchy of the scene that we are going to use is composed by the GameObjects that are shown in figure 2, the object «Script-GameObject» is the one that has the Script in figure 1 assigned and it is the one that will be in charge of finding the references, in figure 3 you can see the inspector of this GameObject, where the Script is assigned.
The «GDT (Object to Find)» object seen in figure 2 is the object we want to find from the script, so if we succeed we should see the name of this object printed on the console.
Find the reference of a GameObject that has a specific component
If we know that the GameObject we are interested in finding has a specific component assigned to it, such as a «Camera», «Rigidbody», «AudioSource» component or a script we have created ourselves, we can use that knowledge to find the GameObject reference.
I will create a script called «SomeScript» and assign it to the GameObject we want to find, as shown in figures 4 and 5.
Using the instruction «FindObjectOfType<T>()», where T is the type of object we are looking for (in our case it is «SomeScript» type), we can find the reference of the «SomeScript» instance that is assigned to that GameObject, then using the dot operator we can access the GameObject to which that Script is assigned.
The instruction that does all this can be seen in line 20 of figure 6.
When this instruction is executed, Unity will check all the objects in the hierarchy and each one of its components until it finds a «SomeScript» type object, when it finds it it returns it as a result, but since we are interested in the GameObject to which that Script is assigned, we use the dot operator and access the «gameObject» field. If there is no object that has the «SomeScript» component assigned to it we will have a null reference error because we are using the «objectToFind» field in line 22 of figure 6.
To keep in mind, if we have more than one GameObject that has assigned the component we are looking for, Unity will return the first component that it finds in its register, in this case ambiguities could arise, we could obtain the reference of a different 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
Вадим МорозВадим Мороз
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
Алексей ШиманскийАлексей Шиманский
72.3k11 золотых знаков87 серебряных знаков173 бронзовых знака
Если у тебя есть инстанс скрипта то
instance.gameObject.Destroy();
Так же можешь сделать public static List с твоими обьектами. А внутри обьекта уже иметь айдишник.
Тогда достаточно просто найти в этом листе через Linq обьект с нужным айдишником и его дестройнуть.
Делать же это через какой-то внешний дикшинари — это как-то костыльно, потому не советую. Костылно потому, как хранить параметр обьекта вне обьекта — нелогично с точки зрения ООП.
ответ дан 28 янв 2017 в 17:37
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 минут
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 |
|||||||
Поиск по компоненту через
Древо строится рекурсивно через
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, компонент задаётся именно в
Я правильно понимаю? Мне нужно находить обекты с
Как мне тогда задать так, чтобы он искал именно их?
0 |
Cr0c 751 / 599 / 203 Регистрация: 06.08.2015 Сообщений: 2,432 |
||||
26.02.2016, 14:04 |
14 |
|||
Naomis, поле — это не компонент!
И работаете с массивом ссылок на эти экземпляры скрипта.
1 |
Naomis 8 / 8 / 4 Регистрация: 11.03.2015 Сообщений: 212 |
||||
26.02.2016, 14:41 [ТС] |
15 |
|||
Cr0c, А, то есть теперь беру «mss » и пробегаюсь по массиву и ищу там объекты с компонентом «string TooltipText». Я правильно понял? Если да, то работать с элементами массива следует через getComponent? То есть:
0 |
Cr0c 751 / 599 / 203 Регистрация: 06.08.2015 Сообщений: 2,432 |
||||
26.02.2016, 15:29 |
16 |
|||
Naomis, Вы плохо знаете синтаксис c# ((( У Вас УЖЕ будут прямые ссылки на компоненты класса MyScript.
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.Теперь в массиве я ищу элементы этим,
«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 |