Как найти скрипт на сцене unity

Найти все скрипты в сцене? [РЕШЕНО]

Найти все скрипты в сцене? [РЕШЕНО]

Доброго времени суток!
Подскажите как можно найти все скрипты в сцене? Зачатки разума подсказывают мне, что сгодится вот это FindObjectsOfType, но я никак не могу понять какой тип у скриптов?! То есть получается найти все кроме скриптов. Заранее благодарен.
Да пребудет с Вами Великий Коннект!

Последний раз редактировалось formurik 30 мар 2012, 17:50, всего редактировалось 1 раз.

Аватара пользователя
formurik
UNIт
 
Сообщения: 73
Зарегистрирован: 31 мар 2011, 14:35

Re: Найти все скрипты в сцене?

Сообщение Good1101 30 мар 2012, 17:42

По идее так можно собрать ссылки на все компоненты одного типа на сцене в массив

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

Object[] GO = FindObjectsOfType(typeof(mySkript));

Хотя я не пробовал, нужно тестить.

Аватара пользователя
Good1101
Адепт
 
Сообщения: 1100
Зарегистрирован: 17 ноя 2011, 14:07
  • ICQ

Re: Найти все скрипты в сцене? [РЕШЕНО]

Сообщение formurik 30 мар 2012, 17:51

Тип MonoBehaviour очень даже подошел. Всем спасибо.

Аватара пользователя
formurik
UNIт
 
Сообщения: 73
Зарегистрирован: 31 мар 2011, 14:35

Re: Найти все скрипты в сцене? [РЕШЕНО]

Сообщение gate1 02 апр 2012, 12:54

Antares Browser позволяет просмотреть все скрипты которые используются в сцене

Аватара пользователя
gate1
UNITрон
 
Сообщения: 198
Зарегистрирован: 27 дек 2011, 22:19
Откуда: Минск


Вернуться в Скрипты

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

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 11



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.

Рассмотрим, как в Unity на языке C# получать доступ из одного скрипта к переменным и функциям других скриптов.

Юнити: Как обратиться к другому скрипту на том же объекте

GetComponent<DrygoiScript>().peremennayaScripta = 5;

Эта «команда» обращается к другому скрипту, который в виде компонента висит на том же объекте, что и скрипт, где вы это пишете. У этого скрипта есть переменная с именем peremennayaScripta, ей присваивается значение 5. Так можно обращаться к любым компонентам вашего игрового объекта, начиная от ваших скриптов, висящих на нем, и заканчивая обычными юнитивскими компонентами — Rigitbody, Animator, Transform и прочими.

Unity: Как получить ссылку на другой скрипт с одного объекта

Но вы можете не писать каждый раз «команду» GetComponent<>, а создать переменную для ссылки на компонент. Пишете:

DrygoiScript peremennayaSsilkaNaDrygoiScript = GetComponent<DrygoiScript>();

Вы тут сначала создали переменную с именем peremennayaSsilkaNaDrygoiScript и тип переменной DrygoiScript (что означает, что туда можно поместить только ссылку на DrygoiScript, но не на любой другой скрипт).

Потом вы через знак «=» присвоили этой переменной ссылку на DrygoiScript, который висит на том же объекте, что и этот скрипт с кодом.

Теперь вы можете написать:

peremennayaSsilkaNaDrygoiScript.peremennayaScripta = 5;

Через peremennayaSsilkaNaDrygoiScript произойдет обращение к тому скрипту (это аналогично GetComponent<DrygoiScript>()), и его переменная peremennayaScripta установится в значение 5. 

Unity3d: как получить ссылку на другой объект

На другом объекте может висеть нужный вам скрипт, и вы хотите изменить его переменные или вызвать его функцию из другого скрипта? Тогда сначала нужно получить ссылку на него. Для этого создаете переменную в исходном скрипте:

public GameObject ssilkaNaObject;

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

 ssilkaNaObject.GetComponent<DrygoiScript>().peremennayaScripta = 5;

Тут вы по ссылке ssilkaNaObject обращаетесь к объекту, который перетянули в инспекторе в переменную ssilkaNaObject, и далее обращаетесь к конкретному компоненту GetComponent<DrygoiScript>(), это нужный вам скрипт, и меняете у этого скрипта переменную под названием peremennayaScripta на 5. Аналогично с вызовом какой-либо функций:

ssilkaNaObject.GetComponent<DrygoiScript>().MyFuction();

Тут вы вызвали функцию с именем MyFuction() в скрипте DrygoiScript, который висит на ssilkaNaObject.

Юнити: как кешировать ссылку на ваш скрипт

Но GetComponent<> ресурсозатратная операция, поэтому лучше сразу создать переменную, чтобы положить туда ссылку на конкретный компонент (ваш скрипт). Ссылку на объект мы уже получили, и она называется ssilkaNaObject, но не получили ссылку на скрипт DrygoiScript, поэтому и приходится каждый раз писать GetComponent<DrygoiScript>().

DrygoiScript peremennayaSsilkaNaDrygoiScript = ssilkaNaObject.GetComponent<DrygoiScript>();

Теперь переменная peremennayaSsilkaNaDrygoiScript будет содержать ссылку на ваш скрипт, который висит на объекте, на который ссылается ssilkaNaObject. И можно без всяких GetComponent писать:

peremennayaSsilkaNaDrygoiScript.peremennayaScripta = 5; // изменение значения переменной в другом скрипте

peremennayaSsilkaNaDrygoiScript.MyFuction(); // вызов функции другого скрипта

Это называется кеширование. Мы с вами закешировали, как сам объект, на котором скрипт, так и ссылку на скрипт. Грубо говоря — кеширование это создание ссылки на нужную вещь, по которой потом можно обращаться к объекту, чтобы не приходилось каждый раз его искать заново.

Юнити3Д: как получить доступ к объекту из другого скрипта

До этого мы нужный нам объект переносили вручную через инспектор Unity в переменную ssilkaNaObject , но получить к нему доступ из кода можно несколькими способами.

public GameObject ssilkaNaObject; // не забывайте создавать переменную, которая будет ссылкой на объект

ssilkaNaObject = GameObject.Find("ИмяОбъектаПоИерархии"); // поиск объекта по имени

Тут в переменную ssilkaNaObject мы заносим то, что найдет компьютер по имени в иерархии сцены Unity. Минус в том, что придется запоминать, что переименовывать объект нельзя.

ssilkaNaObject = GameObject.FindGameObjectWithTag("Player"); // поиск объекта по тегу


Так мы получим ссылку на первый объект, который найдет компьютер по тегу Player (задается в инспекторе). Если объектов несколько с одним тегом, то в ссылку компьютер положит первый попавшийся.

Советы

Все операции, когда вы переменной присваиваете ссылку на объект или компонент (скрипт) проводят, как правило, в методе Start. Сами переменные создаются вне методов, чтобы они были доступны по всему скрипту, а не были локальными в каком-то методе. А значения им присваиваются в методе Start, который срабатывает когда запускается сцена, тогда Unity3d и найдет нужный объекты, и запишет в ваши переменные ссылки на них. Например:

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

public class TestPoiskObjectov : MonoBehaviour {

  // это место вне каких-либо методов
  
    public GameObject ssilkaNaObject; // не забывайте создавать переменную, которая будет ссылкой на объект
    public DrygoiScript peremennayaSsilkaNaDrygoiScript; // переменная для ссылки на конкретный скрипт

    void Start () {
       // поиск объекта по имени
        ssilkaNaObject = GameObject.Find("ИмяОбъектаПоИерархии");
      
      // получение ссылки на компонент с другого объекта
        DrygoiScript peremennayaSsilkaNaDrygoiScript = ssilkaNaObject.GetComponent<DrygoiScript>();
    }
	
	void Update () {
		
	}
}


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using UnityEngine.SceneManagement; //3
public class SelectGameObjectsWithMissingScripts : Editor
{
[MenuItem(«Tools/WPAG Utilities/Select GameObjects With Missing Scripts«)]
static void SelectGameObjects()
{
//Get the current scene and all top-level GameObjects in the scene hierarchy
Scene currentScene = SceneManager.GetActiveScene();
GameObject[] rootObjects = currentScene.GetRootGameObjects();
List<Object> objectsWithDeadLinks = new List<Object>();
foreach (GameObject g in rootObjects)
{
//Get all components on the GameObject, then loop through them
Component[] components = g.GetComponents<Component>();
for (int i = 0; i < components.Length; i++)
{
Component currentComponent = components[i];
//If the component is null, that means it’s a missing script!
if (currentComponent == null)
{
//Add the sinner to our naughty-list
objectsWithDeadLinks.Add(g);
Selection.activeGameObject = g;
Debug.Log(g + « has a missing script!«);
break;
}
}
}
if (objectsWithDeadLinks.Count > 0)
{
//Set the selection in the editor
Selection.objects = objectsWithDeadLinks.ToArray();
}
else
{
Debug.Log(«No GameObjects in ‘« + currentScene.name + «‘ have missing scripts! Yay!«);
}
}
}

Сообщество Программистов

Загрузка…

Понравилась статья? Поделить с друзьями:
  • Портал нмо как найти сертификат
  • Как найти свою любимую девочку
  • Как найти косинус зная только тангенс
  • Как исправить обновление вин 10
  • Как найти объем пирамиды с основанием треугольник