Important Classes — GameObject
Unity’s GameObject class represents anything which can exist in a Scene A Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary .
This page relates to scripting with Unity’s GameObject class. To learn about using GameObjects in the Scene and Hierarchy in the Unity Editor, see the GameObjects section of the user manual. For an exhaustive reference of every member of the GameObject class, see the GameObject script reference.
GameObjects are the building blocks for scenes in Unity, and act as a container for functional components which determine how the GameObject looks, and what the GameObject does.
In scripting, the GameObject class provides a collection of methods which allow you to work with them in your code, including finding, making connections and sending messages between GameObjects, and adding or removing components attached to the GameObject, and setting values relating to their status within the scene.
Scene Status properties
You can use scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary to modify many properties related to a GameObject’s status in the scene. These typically correspond to the controls visible near the top of the inspector A Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary when you have a GameObject selected in the Editor.
They don’t relate to any particular component, and are visible in the inspector of a GameObject at the top, above the list of components.
A typical GameObject viewed in the Inspector. In this case, a directional light. The Scene status properties are outlined in red.
All GameObjects share a set of controls at the top of the inspector relating to the GameObject’s status within the scene, and these can be controlled via the GameObject’s scripting API.
If you want a quick list of all the available API for the GameObject class, see the GameObject Script Reference.
Active Status
The Active status of a GameObject
GameObjects are active by default, but can be deactivated, which turns off all components attached to the GameObject. This generally means it will become invisible, and not receive any of the normal callbacks or events such as Update or FixedUpdate .
The GameObject’s active status is represented by the checkbox to the left of the GameObject’s name. You can control this using GameObject.SetActive .
You can also use GameObject.activeSelf to read the current active state of a GameObject. Use GameObject.activeInHierarchy to read whether the GameObject is actually active in the scene. GameObject.activeInHierarchy is necessary because whether a GameObject is actually active is determined by its own active state and the active state of all of its parents. If any of its parents aren’t active, then it’s not active despite its own active setting.
Static Status
The Static status of a GameObject
Some of Unity’s systems, such as Global Illumination A group of techniques that model both direct and indirect lighting to provide realistic lighting results.
See in Glossary , Occlusion, Batching, Navigation, and Reflection Probes A rendering component that captures a spherical view of its surroundings in all directions, rather like a camera. The captured image is then stored as a Cubemap that can be used by objects with reflective materials. More info
See in Glossary , rely on the static status of a GameObject. You can control which of Unity’s systems consider the GameObject to be static by using GameObjectUtility.SetStaticEditorFlags . Read more about Static GameObjects here.
Tags and Layers
The Tag and Layer fields of a GameObject
Tags provide a way of marking and identifying types of GameObject in your scene and Layers provide a similar but distinct way of including or excluding groups of GameObjects from certain built-in actions, such as rendering or physics collisions.
For more information about how to use Tags and Layers in the editor, see the main user manual pages for Tags A reference word which you can assign to one or more GameObjects to help you identify GameObjects for scripting purposes. For example, you might define and “Edible” Tag for any item the player can eat in your game. More info
See in Glossary and Layers Layers in Unity can be used to selectively opt groups of GameObjects in or out of certain processes or calculations. This includes camera rendering, lighting, physics collisions, or custom calculations in your own code. More info
See in Glossary .
You can modify tag and layer values via script using the GameObject.tag and GameObject.layer properties. You can also check a GameObject’s tag efficiently by using the CompareTag method, which includes validation of whether the tag exists, and doesn’t cause any memory allocation.
Adding and Removing components
You can add or remove components at runtime, which can be useful for procedurally creating GameObjects, or modifying how a GameObject behaves. Note, you can also enable or disable script components, and some types of built-in component, via script without destroying them.
The best way to add a component at runtime is to use AddComponent<Type> , specifying the type of component within angle brackets as shown. To remove a component, you must use Object.Destroy method on the component itself.
Accessing components
The simplest case is where a script on a GameObject needs to access another Component attached to the same GameObject (remember, other scripts attached to a GameObject are also Components themselves). To do this, the first step is to get a reference to the Component instance you want to work with. This is done with the GetComponent method. Typically, you want to assign the Component object to a variable, which is done in using the following code. In this example the script is getting a reference to a Rigidbody A component that allows a GameObject to be affected by simulated gravity and other forces. More info
See in Glossary component on the same GameObject:
Once you have a reference to a Component instance, you can set the values of its properties much as you would in the Inspector:
You can also call methods on the Component reference, for example:
Note: you can have multiple custom scripts attached to the same GameObject. If you need to access one script from another, you can use GetComponent as usual and just use the name of the script class (or the filename) to specify the Component type you want.
If you attempt to retrieve a Component type that hasn’t actually been added to the GameObject then GetComponent will return null; you will get a null reference error at runtime if you try to change any values on a null object.
Accessing components on other GameObjects
Although they sometimes operate in isolation, it’s common for scripts to keep track of other GameObjects, or more commonly, components on other GameObjects. For example, in a cooking game, a chef might need to know the position of the stove. Unity provides a number of different ways to retrieve other objects, each appropriate to certain situations.
Linking to GameObjects with variables in the inspector
The most straightforward way to find a related GameObject is to add a public GameObject variable to the script:
This variable will be visible in the Inspector, as a GameObject field.
You can now drag an object from the scene or Hierarchy panel onto this variable to assign it.
Dragging a Prefab from the Project window into a GameObject field in the Inspector window
The GetComponent function and Component access variables are available for this object as with any other, so you can use code like the following:
Additionally, if you declare a public variable of a Component type in your script, you can drag any GameObject that has that Component attached onto it. This accesses the Component directly rather than the GameObject itself.
Linking objects together with variables is most useful when you are dealing with individual objects that have permanent connections. You can use an array variable to link several objects of the same type, but the connections must still be made in the Unity editor rather than at runtime. It’s often convenient to locate objects at runtime and Unity provides two basic ways to do this, as described below.
Finding child GameObjects
Sometimes, a game Scene makes use of a number of GameObjects of the same type, such as collectibles, waypoints and obstacles. These might need to be tracked by a particular script that supervises or reacts to them (for example, all waypoints might need to be available to a pathfinding script). Using variables to link these GameObjects is a possibility but it makes the design process tedious if each new waypoint has to be dragged to a variable on a script. Likewise, if a waypoint is deleted, then it’s a nuisance to have to remove the variable reference to the missing GameObject. In cases like this, it is often better to manage a set of GameObjects by making them all children of one parent GameObject. The child GameObjects can be retrieved using the parent’s Transform component A Transform component determines the Position, Rotation, and Scale of each object in the scene. Every GameObject has a Transform. More info
See in Glossary (because all GameObjects implicitly have a Transform):
You can also locate a specific child object by name using the Transform.Find method: transform.Find("Frying Pan");
This can be useful when a GameObject has a child GameObject that can be added and removed during gameplay. A tool or utensil that can be picked up and put down during gameplay is a good example of this.
Sending and Broadcasting messages
While editing your project you can set up references between GameObjects in the Inspector. However, sometimes it’s impossible to set up these in advance (for example, finding the nearest item to a character in your game, or making references to GameObjects that were instantiated after the Scene loaded). In these cases, you can find references and send messages between GameObjects at runtime.
BroadcastMessage allows you to send out a call to a named method, without being specific about where that method should be implemented. You can use it to call a named method on every MonoBehaviour on a particular GameObject or any of its children. You can optionally choose to enforce that there must be at least one receiver (or an error is generated).
SendMessage is a little more specific, and only sends the call to a named method on the GameObject itself, and not its children.
SendMessageUpwards is similar, but sends out the call to a named method on the GameObject and all its parents.
Finding GameObjects by Name or Tag
It’s always possible to locate GameObjects anywhere in the Scene hierarchy as long as you have some information to identify them. Individual objects can be retrieved by name using the GameObject.Find function:
An object or a collection of objects can also be located by their tag using the GameObject.FindWithTag and GameObject.FindGameObjectsWithTag methods.
For example, in a cooking game with one chef character, and multiple stoves in the kitchen (each tagged “Stove”):
Creating and Destroying GameObjects
You can create and destroy GameObjects while your project is running. In Unity, a GameObject can be created using the Instantiate method which makes a new copy of an existing object.
For a full description and examples of how to instantiate GameObjects, see Instantiating Prefabs at Runtime.
The Destroy method destroys an object after the frame update has finished or optionally after a short time delay:
Note that the Destroy function can destroy individual components and not affect the GameObject itself. A common mistake is to write this and assume it destroys the GameObject the script is attached to:
this represents the script, and not the GameObject. It will actually just destroy the script component that calls it and leave the GameObject intact but with the script component removed.
Primitives
The GameObject class offers script-based alternatives to the options available in Unity’s GameObject menu that allows you to create primitive objects.
To create instances of Unity’s built-in primitives, use GameObject.CreatePrimitive, which instantiates a primitive of the type that you specify. The available primitive types are Sphere, Capsule, Cylinder, Cube, Plane and Quad A primitive object that resembles a plane but its edges are only one unit long, it uses only 4 vertices, and the surface is oriented in the XY plane of the local coordinate space. More info
See in Glossary .
The Primitive shapes available in Unity’s GameObject menu
Important Classes — GameObject
Unity’s GameObject class is used to represent anything which can exist in a Scene A Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary .
This page relates to scripting with Unity’s GameObject class. To learn about using GameObjects in the Scene and Hierarchy in the Unity Editor, see the GameObjects section of the user manual. For an exhaustive reference of every member of the GameObject class, see the GameObject script reference.
GameObjects are the building blocks for scenes in Unity, and act as a container for functional components which determine how the GameObject looks, and what the GameObject does.
In scripting, the GameObject class provides a collection of methods which allow you to work with them in your code, including finding, making connections and sending messages between GameObjects, as well as adding or removing components attached to the GameObject, and setting values relating to their status within the scene.
Scene Status properties
There are a number of properties you can modify via script which relate to the GameObject’s status in the scene. These typically correspond to the controls visible near the top of the inspector A Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary when you have a GameObject selected in the Editor.
They don’t relate to any particular component, and are visible in the inspector of a GameObject at the top, above the list of components.
A typical GameObject viewed in the Inspector. In this case, a directional light. The Scene status properties are outlined in red.
All GameObjects share a set of controls at the top of the inspector relating to the GameObject’s status within the scene, and these can be controlled via the GameObject’s scripting API.
If you want a quick list of all the available API for the GameObject class, see the GameObject Script Reference.
Active Status
The Active status of a GameObject
GameObjects are active by default, but can be deactivated, which turns off all components attached to the GameObject. This generally means it will become invisible, and not receive any of the normal callbacks or events such as Update or FixedUpdate .
The GameObject’s active status is represented by the checkbox to the left of the GameObject’s name. You can control this using GameObject.SetActive .
You can also read the current active state using GameObject.activeSelf , and whether or not the GameObject is actually active in the scene using GameObject.activeInHierarchy . The latter of these two is necessary because whether a GameObject is actually active is determined by its own active state, plus the active state of all of its parents. If any of its parents are not active, then it will not be active despite its own active setting.
Static Status
The Static status of a GameObject
Some of Unity’s systems, such as Global Illumination A group of techniques that model both direct and indirect lighting to provide realistic lighting results.
See in Glossary , Occlusion, Batching, Navigation, and Reflection Probes A rendering component that captures a spherical view of its surroundings in all directions, rather like a camera. The captured image is then stored as a Cubemap that can be used by objects with reflective materials. More info
See in Glossary , rely on the static status of a GameObject. You can control which of Unity’s systems consider the GameObject to be static by using GameObjectUtility.SetStaticEditorFlags . Read more about Static GameObjects here.
Tags and Layers
The Static status of a GameObject
Tags provide a way of marking and identifying types of GameObject in your scene and Layers provide a similar but distinct way of including or excluding groups of GameObjects from certain built-in actions, such as rendering or physics collisions.
For more information about how to use Tags and Layers in the editor, see the main user manual pages for Tags A reference word which you can assign to one or more GameObjects to help you identify GameObjects for scripting purposes. For example, you might define and “Edible” Tag for any item the player can eat in your game. More info
See in Glossary and Layers Layers in Unity can be used to selectively opt groups of GameObjects in or out of certain processes or calculations. This includes camera rendering, lighting, physics collisions, or custom calculations in your own code. More info
See in Glossary .
You can modify tag and layer values via script using the GameObject.tag and GameObject.layer properties. You can also check a GameObject’s tag efficiently by using the CompareTag method, which includes validation of whether the tag exists, and does not cause any memory allocation.
Adding and Removing components
You can add or remove components at runtime, which can be useful for procedurally creating GameObjects, or modifying how a GameObject behaves. Note, you can also enable or disable script components, and some types of built-in component, via script without destroying them.
The best way to add a component at runtime is to use AddComponent<Type> , specifying the type of component within angle brackets as shown. To remove a component, you must use Object.Destroy method on the component itself.
Accessing components
The simplest case is where a script on a GameObject needs to access another Component attached to the same GameObject (remember, other scripts attached to a GameObject are also Components themselves). To do this, the first step is to get a reference to the Component instance you want to work with. This is done with the GetComponent method. Typically, you want to assign the Component object to a variable, which is done in using the following code. In this example the script is getting a reference to a Rigidbody A component that allows a GameObject to be affected by simulated gravity and other forces. More info
See in Glossary component on the same GameObject:
Once you have a reference to a Component instance, you can set the values of its properties much as you would in the Inspector:
You can also call methods on the Component reference, for example:
Note: you can have multiple custom scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary attached to the same GameObject. If you need to access one script from another, you can use GetComponent as usual and just use the name of the script class (or the filename) to specify the Component type you want.
If you attempt to retrieve a Component type that hasn’t actually been added to the GameObject then GetComponent will return null; you will get a null reference error at runtime if you try to change any values on a null object.
Accessing components on other GameObjects
Although they sometimes operate in isolation, it is common for scripts to keep track of other GameObjects, or more commonly, components on other GameObjects. For example, in a cooking game, a chef might need to know the position of the stove. Unity provides a number of different ways to retrieve other objects, each appropriate to certain situations.
Linking to GameObjects with variables in the inspector
The most straightforward way to find a related GameObject is to add a public GameObject variable to the script:
This variable will be visible in the Inspector, as a GameObject field.
You can now drag an object from the scene or Hierarchy panel onto this variable to assign it.
Dragging a Prefab from the Project window into a GameObject field in the Inspector window
The GetComponent function and Component access variables are available for this object as with any other, so you can use code like the following:
Additionally, if you declare a public variable of a Component type in your script, you can drag any GameObject that has that Component attached onto it. This accesses the Component directly rather than the GameObject itself.
Linking objects together with variables is most useful when you are dealing with individual objects that have permanent connections. You can use an array variable to link several objects of the same type, but the connections must still be made in the Unity editor rather than at runtime. It is often convenient to locate objects at runtime and Unity provides two basic ways to do this, as described below.
Finding child GameObjects
Sometimes, a game Scene makes use of a number of GameObjects of the same type, such as collectibles, waypoints and obstacles. These may need to be tracked by a particular script that supervises or reacts to them (for example, all waypoints might need to be available to a pathfinding script). Using variables to link these GameObjects is a possibility but it makes the design process tedious if each new waypoint has to be dragged to a variable on a script. Likewise, if a waypoint is deleted, then it is a nuisance to have to remove the variable reference to the missing GameObject. In cases like this, it is often better to manage a set of GameObjects by making them all children of one parent GameObject. The child GameObjects can be retrieved using the parent’s Transform component A Transform component determines the Position, Rotation, and Scale of each object in the scene. Every GameObject has a Transform. More info
See in Glossary (because all GameObjects implicitly have a Transform):
You can also locate a specific child object by name using the Transform.Find method: transform.Find("Frying Pan");
This can be useful when a GameObject has a child GameObject that can be added and removed during gameplay. A tool or utensil that can be picked up and put down during gameplay is a good example of this.
Sending and Broadcasting messages
While editing your project you can set up references between GameObjects in the Inspector. However, sometimes it is impossible to set up these in advance (for example, finding the nearest item to a character in your game, or making references to GameObjects that were instantiated after the Scene loaded). In these cases, you can find references and send messages between GameObjects at runtime.
BroadcastMessage allows you to send out a call to a named method, without being specific about where that method should be implemented. You can use it to call a named method on every MonoBehaviour on a particular GameObject or any of its children. You can optionally choose to enforce that there must be at least one receiver (or an error is generated).
SendMessage is a little more specific, and only sends the call to a named method on the GameObject itself, and not its children.
SendMessageUpwards is similar, but sends out the call to a named method on the GameObject and all its parents.
Finding GameObjects by Name or Tag
It is always possible to locate GameObjects anywhere in the Scene hierarchy as long as you have some information to identify them. Individual objects can be retrieved by name using the GameObject.Find function:
An object or a collection of objects can also be located by their tag using the GameObject.FindWithTag and GameObject.FindGameObjectsWithTag methods.
For example, in a cooking game with one chef character, and multiple stoves in the kitchen (each tagged “Stove”):
Creating and Destroying GameObjects
You can create and destroy GameObjects while your project is running. In Unity, a GameObject can be created using the Instantiate method which makes a new copy of an existing object.
For a full description and examples of how to instantiate GameObjects, see Instantiating Prefabs at Runtime.
There is also a Destroy method that will destroy an object after the frame update has finished or optionally after a short time delay:
Note that the Destroy function can destroy individual components without affecting the GameObject itself. A common mistake is to write this, assuming it will destroy the GameObject the script it’s attached to…
…whereas, because “this” represents the script, and not the GameObject, it will actually just destroy the script component that calls it, leaving the GameObject behind, with the script component removed.
Primitives
The GameObject class offers script-based alternatives to the options available in Unity’s GameObject menu that allows you to create primitive objects.
To create instances of Unity’s built-in primitives, use GameObject.CreatePrimitive, which instantiates a primitive of the type that you specify. The available primitive types are Sphere, Capsule, Cylinder, Cube, Plane and Quad A primitive object that resembles a plane but its edges are only one unit long, it uses only 4 vertices, and the surface is oriented in the XY plane of the local coordinate space. More info
See in Glossary .
The Primitive shapes available in Unity’s GameObject menu
Важные классы — GameObject
Класс Unity GameObject используется для представления всего, что может существовать в Сцене Сцена содержит окружение и меню вашей игры. Думайте о каждом уникальном файле сцены как об уникальном уровне. В каждой сцене вы размещаете свое окружение, препятствия и декорации, по сути проектируя и создавая свою игру по частям. Подробнее
См. в Словарь .
Эта страница относится к скриптам с классом GameObject Unity. Чтобы узнать об использовании игровых объектов в сцене и иерархии в редакторе Unity, см. раздел GameObjects руководства пользователя. Исчерпывающую информацию о каждом члене класса GameObject см. в справочнике по сценариям GameObject.
GameObjects — это стандартные блоки для сцен в Unity, которые служат контейнером для функциональных компонентов, определяющих, как выглядит GameObject и что делает GameObject.
В сценариях класс GameObject предоставляет набор методов, которые позволяют работать с ними в коде, включая поиск, установление соединений и отправку сообщений. между игровыми объектами, а также добавлять или удалять компоненты, прикрепленные к игровым объектам, и устанавливать значения, относящиеся к их статусу в сцене.
Свойства статуса сцены
С помощью скрипта можно изменить ряд свойств, которые относятся к статусу игрового объекта в сцене. Обычно они соответствуют элементам управления, видимым в верхней части инспектора окна Unity, в котором отображается информация о текущем выбранном игровом объекте, активе или настройки проекта, позволяющие просматривать и редактировать значения. Дополнительная информация
См. в Словарь , когда в редакторе выбран GameObject.
Они не относятся к какому-либо конкретному компоненту и отображаются в инспекторе GameObject вверху над списком компонентов.
Типичный GameObject, просматриваемый в Инспекторе. В данном случае направленный свет. Свойства состояния сцены обведены красным.
Все игровые объекты имеют общий набор элементов управления в верхней части инспектора, относящихся к статусу игрового объекта в сцене, и ими можно управлять с помощью API сценариев игрового объекта.
Если вам нужен краткий список всех доступных API для класса GameObject, см. Справочник по скриптам GameObject.
Активный статус
Активный статус GameObject
Игровые объекты активны по умолчанию, но их можно деактивировать, что приведет к отключению всех компонентов, прикрепленных к игровым объектам. Обычно это означает, что он станет невидимым и не будет получать какие-либо обычные обратные вызовы или события, такие как Update или FixedUpdate .
Статус игрового объекта активен представлен флажком слева от имени игрового объекта. Вы можете управлять этим с помощью GameObject.SetActive .
Вы также можете прочитать текущее активное состояние с помощью GameObject.activeSelf , а также не GameObject действительно активен в сцене с использованием GameObject.activeInHierarchy . Последнее из этих двух необходимо, потому что действительно ли GameObject активен, определяется его собственным активным состоянием плюс активным состоянием всех его родителей. Если какой-либо из его родителей неактивен, он не будет активен, несмотря на его собственную активную настройку.
Статический статус
Статический статус GameObject
Некоторые системы Unity, такие как Global Illumination группа методов, которые моделируют как прямое, так и непрямое освещение для обеспечения реалистичного освещения. полученные результаты. В Unity есть две системы глобального освещения, сочетающие прямое и непрямое освещение: запеченное глобальное освещение и глобальное освещение в реальном времени.
См. в Словарь , Окклюзия, Пакетная обработка, Навигация и Reflection Probes Компонент рендеринга, который захватывает сферическое изображение своего окружения во всех направлениях, подобно камере. Захваченное изображение затем сохраняется как кубическая карта, которую можно использовать для объектов с отражающими материалами. Подробнее
См. в Словарь , полагайтесь на статический статус GameObject. Вы можете указать, какие из систем Unity будут считать GameObject статическими, используя GameObjectUtility.SetStaticEditorFlags . Узнайте больше о статических игровых объектах здесь.
Теги и слои
Статический статус GameObject
Теги обеспечивают способ маркировки и идентификации типов игровых объектов в вашей сцене, а слои обеспечивают аналогичный, но отличный способ включения или исключения групп игровых объектов из определенных встроенных элементов. в действиях, таких как рендеринг процесс вывода графики на экран ( или к текстуре рендера). По умолчанию основная камера в Unity отображает изображение на экране. Подробнее
См. Словарь или физические коллизии.
Дополнительную информацию об использовании тегов и слоев в редакторе см. на основных страницах руководства пользователя для тегов. Опорное слово, которое вы можете присвоить одному или нескольким игровым объектам, чтобы помочь вам идентифицировать игровые объекты для сценариев. Например, вы можете определить тег «Съедобный» для любого предмета, который игрок может съесть в вашей игре. Подробнее
См. в Словарь и Слои Слои в Unity можно использовать для выборочного включения или исключения групп игровых объектов из определенных процессов или вычислений. Это включает в себя рендеринг камеры, освещение, физические коллизии или пользовательские вычисления в вашем собственном коде. Подробнее
См. в Словарь .
Вы можете изменить значения тегов и слоев с помощью скрипта, используя GameObject.tag и GameObject.layer . Вы также можете эффективно проверить тег GameObject с помощью метода CompareTag , который включает проверку того, тег существует и не вызывает выделения памяти.
Добавление и удаление компонентов
Вы можете добавлять или удалять компоненты во время выполнения, что может быть полезно для процедурного создания игровых объектов или изменения поведения игрового объекта. Обратите внимание, что вы также можете включить или отключить компоненты скрипта и некоторые типы встроенных компонентов через скрипт без их уничтожения.
Лучший способ добавить компонент во время выполнения — использовать AddComponent , указав тип компонента в угловых скобках, как показано. Чтобы удалить компонент, вы должны использовать метод Object.Destroy для самого компонента.
Доступ к компонентам
Самый простой случай — когда скрипту игрового объекта требуется доступ к другому компоненту, прикрепленному к тому же игровому объекту (помните, что другие скрипты, прикрепленные к игровому объекту, также сами являются компонентами). Для этого первым делом необходимо получить ссылку на экземпляр компонента, с которым вы хотите работать. Это делается с помощью метода GetComponent. Как правило, вы хотите присвоить объект Component переменной, что делается с помощью следующего кода. В этом примере скрипт получает ссылку на Rigidbody компонент, который позволяет моделируемой гравитации и другим силам воздействовать на GameObject. . Подробнее
См. в компоненте Словарь на том же GameObject:
Once you have a reference to a Component instance, you can set the values of its properties much as you would in the Inspector:
Вы также можете вызывать методы для ссылки на компонент, например:
Примечание: у вас может быть несколько пользовательских скриптов фрагмент кода, который позволяет создавать собственные компоненты, запускающие игровые события , изменяйте свойства компонента с течением времени и реагируйте на ввод данных пользователем любым удобным для вас способом. Подробнее
См. Словарь , прикрепленный к тому же GameObject. Если вам нужно получить доступ к одному скрипту из другого, вы можете использовать GetComponent как обычно и просто использовать имя класса скрипта (или имя файла), чтобы указать нужный тип компонента.
Если вы попытаетесь получить тип компонента, который на самом деле не был добавлен в GameObject, GetComponent вернет значение null; вы получите ошибку нулевой ссылки во время выполнения, если попытаетесь изменить какие-либо значения нулевого объекта.
Доступ к компонентам других игровых объектов
Хотя иногда они работают изолированно, сценарии обычно отслеживают другие игровые объекты или, чаще, компоненты других игровых объектов. Например, в кулинарной игре повару может понадобиться знать положение плиты. Unity предоставляет несколько различных способов извлечения других объектов, каждый из которых подходит для определенных ситуаций.
Связывание с игровыми объектами с помощью переменных в инспекторе
Самый простой способ найти связанный GameObject — добавить в скрипт общедоступную переменную GameObject:
Эта переменная будет видна в Инспекторе как поле GameObject.
Теперь вы можете перетащить объект со сцены или панели иерархии на эту переменную, чтобы назначить ее.
Перетаскивание префаба из окна проекта в поле GameObject в окне инспектора
Функция GetComponent и переменные доступа к компоненту доступны для этого объекта, как и для любого другого, поэтому вы можете использовать следующий код:
Кроме того, если вы объявите общедоступную переменную типа Компонент в своем скрипте, вы сможете перетащить любой GameObject, к которому прикреплен этот Компонент. Это напрямую обращается к компоненту, а не к самому игровому объекту.
public Transform playerTransform;
Связывание объектов вместе с переменными наиболее полезно, когда вы имеете дело с отдельными объектами, имеющими постоянные связи. Вы можете использовать переменную массива, чтобы связать несколько объектов одного типа, но соединения все равно должны выполняться в редакторе Unity, а не во время выполнения. Часто удобно находить объекты во время выполнения, и Unity предоставляет два основных способа сделать это, как описано ниже.
Поиск дочерних игровых объектов
Иногда игровая сцена использует несколько игровых объектов одного типа, таких как предметы коллекционирования, путевые точки и препятствия. Их может потребоваться отслеживать с помощью определенного сценария, который контролирует их или реагирует на них (например, может потребоваться, чтобы все путевые точки были доступны для сценария поиска пути). Использование переменных для связывания этих игровых объектов возможно, но это делает процесс проектирования утомительным, если каждую новую путевую точку нужно перетаскивать в переменную в сценарии. Точно так же, если путевая точка удалена, то удаление ссылки переменной на отсутствующий объект GameObject является неприятностью. В подобных случаях часто лучше управлять набором игровых объектов, сделав их дочерними элементами одного родительского игрового объекта. Дочерние игровые объекты можно получить с помощью родительского компонента Transform Компонент Transform определяет положение, вращение и масштаб каждого объекта в сцена. Каждый GameObject имеет Transform. Подробнее
См. в Словарь (поскольку все игровые объекты неявно имеют преобразование):
Вы также можете найти определенный дочерний объект по имени, используя метод Transform.Find: transform.Find («Сковорода»);
Это может быть полезно, когда у GameObject есть дочерний GameObject, который можно добавлять и удалять во время игры. Хорошим примером этого является инструмент или посуда, которые можно взять и положить во время игры.
Отправка и трансляция сообщений
Во время редактирования проекта вы можете установить ссылки между игровыми объектами в Инспекторе. Однако иногда невозможно настроить их заранее (например, найти ближайший к персонажу предмет в вашей игре или сделать ссылки на игровые объекты, экземпляры которых были созданы после загрузки сцены). В этих случаях вы можете находить ссылки и отправлять сообщения между игровыми объектами во время выполнения.
BroadcastMessage позволяет отправить вызов именованному методу, не уточняя о том, где этот метод должен быть реализован. Вы можете использовать его для вызова именованного метода для каждого MonoBehaviour в конкретном GameObject или любом из его дочерних элементов. При желании вы можете указать, что должен быть хотя бы один получатель (иначе будет сгенерирована ошибка).
SendMessage немного более конкретен и отправляет вызов только именованному методу. на самом GameObject, а не на его дочерних элементах.
SendMessageUpwards аналогичен, но отправляет вызов именованного метода в GameObject и все его родители.
Поиск игровых объектов по имени или тегу
Всегда можно найти игровые объекты в любом месте иерархии сцен, если у вас есть информация для их идентификации. Отдельные объекты можно получить по имени с помощью функции GameObject.Find:
GameObject player; void Start()
Объект или набор объектов также можно найти по их тегу с помощью GameObject.FindWithTag и GameObject.FindGameObjectsWithTag.
Например, в кулинарной игре с одним персонажем-поваром и несколькими плитами на кухне (каждая из которых помечена как «Плита»):
GameObject chef; GameObject[] stoves; void Start()
Создание и уничтожение игровых объектов
Вы можете создавать и уничтожать игровые объекты во время работы вашего проекта. В Unity GameObject можно создать с помощью метода Instantiate, который создает новую копию существующего объекта.
Полное описание и примеры создания экземпляров GameObject см. в разделе Создание экземпляров префабов во время выполнения.
Существует также метод Destroy, который уничтожит объект после завершения обновления кадра или, опционально, после небольшой задержки:
Обратите внимание, что функция Destroy может уничтожать отдельные компоненты, не затрагивая сам GameObject. Распространенной ошибкой является написание этого, предполагая, что это уничтожит GameObject скрипт, к которому он прикреплен…
…принимая во внимание, что, поскольку «это» представляет сценарий, а не игровой объект, на самом деле он просто уничтожит вызывающий его компонент сценария, оставив игровой объект позади, а компонент сценария будет удален.
Примитивы
Класс GameObject предлагает основанные на сценариях альтернативы параметрам, доступным в меню GameObject Unity, что позволяет создавать примитивные объекты.
Чтобы создать экземпляры встроенных примитивов Unity, используйте GameObject.CreatePrimitive, который создает экземпляр примитива того типа, который вы указываете. Доступные примитивные типы: Sphere, Capsule, Цилиндр, Куб, Плоскость и Quad Примитивный объект, напоминает плоскость, но его ребра имеют длину всего одну единицу, он использует только 4 вершины, а поверхность ориентирована в плоскости XY локального координатного пространства. Подробнее
См. в Словарь .
Примитивные формы, доступные в меню Unity GameObject
Unity3d. Уроки от Unity 3D Student (B04-B08)
Теперь в каждом посте в скобках (в конце) будут указываться номера уроков. Буква в начале номера обозначает раздел (B-Beginner, I — Intermediate).
PS: Если вы не проходили предыдущие уроки, очень рекомендую их пройти, т.к. последующие изредка на них ссылаются.
Базовый Урок 04 — Уничтожение объектов
В уроке рассказывается как удалять объекты со сцены, использую команду Destroy (уничтожить).
Создайте пустую сцену и добавьте в нее сферу (GameObject->Create Other->Sphere) и куб (GameObject->Create Other->Cube). Куб назовем “Box”. Расположите объекты как показано на рисунке ниже. 
Добавьте C#-Скрипт (Project View->Create->C# Script) и назовите его Destroyer. Как уже говорилось, при создании C#-скрипта Unity создает некий каркас, состоящий из подключенных библиотек и основного класса (используемого скриптом) с методами Start() и Update(). В Базовом Уроке 02 (основы ввода) использовался метод Update(), который вызывается каждый кадр. В данном случае мы воспользуемся методом Start(), который выполняется сразу после загрузки сцены. Добавим в тело метода Start() функцию Destroy() и передадим в нее gameObject, указав таким образом, что скрипт должен уничтожить объект, компонентом которого он является:
Добавим скрипт к сфере. Сделать это можно несколькими путями. Перетащив скрипт из Project View на сферу в Scene View. 
Или на имя объекта в Hierarchy. 

Так же можно выбрать сферу и добавить скрипт через меню компонентов (Component->Scripts->Destroyer) или просто перетащив скрипт в Inspector View выбранного объекта.
Снова выберите сферу и убедитесь, что среди компонентов присутствует ваш скрипт. 
Нажмите на Play и вы увидите, что сразу после загрузки сцены сфера исчезает. 
Давайте теперь попробуем уничтожить другой объект. Для этого нам понадобится статический метод Find класса GameObject. Заменим код в методе Start() следующим:
Примечание от автора перевода: Обратите внимание, что во втором случае мы передаем значение, вызывая статическую функцию, поэтому пишем имя класса (GameObject — с большой буквы), в то время как в первом мы передаем объект этого класса (gameObject — с маленькой буквы). В противном случае компилятор выдаст ошибку:
error CS0176: Static member `UnityEngine.GameObject.Find(string)’ cannot be accessed with an instance reference, qualify it with a type name instead
что переводится как:
“статический член UnityEngine.GameObject.Find(string) не может быть доступен по ссылки экземпляра (класса), вместо этого определите (вызовите) его с именем типа.”
Сохраним изменения в коде скрипта. Скрипт не требуется убирать со сферы и добавлять к нашему кубу, т.к. назависимо от того, к какому объекту он теперь прикреплен, скрипт будет искать любой объект (на сцене) с именем Box. Нажмем Play и увидим как теперь сфера остается в сцене, а куб пропадает. 
Что делать, если нам требуется уничтожить объект не сразу, а спустя какое-то время? Это можно сделать передав значение во 2ой параметр функции Destroy:
Нажмите Play и убедитесь, что куб изчезает через 3и секунды после того, как сцена целиком загрузится.
Дополнительные материалы:
Базовый Урок 05 — Реализация создание объектов
В уроке рассказывается как создавать объекты в сцене в реальном времени (runtime), используя префабы и команду Instantiate (инстанциирование)
Если вы хотите добавлять объекты на сцену, когда сцена уже загружена, то вам требуется использовать скрипты, а точнее команду Instantiate().
Загрузите сцену из Базового урока 03 (Префабы) или создайте такую же новую. В нашей сцене присутствует префаб BouncyBox. 
Нажмите Play и убедитесь, что куб по-прежнему падает и отталкивается от поверхностей.
Теперь удалите со сцены экземпляр BouncyBox. 
После этого добавьте пустой объект (напоминаю, GameObject->Create Empty или Ctrl + Shift + N в Windows, Cmd + Shift + N в MacOS). Расположите его примерно в том месте, где раньше был экземпляр BouncyBox. 
Создадим C#-Скрипт и назовем его Creater. Начнем редактирование скрипта. Заведем открытую (public) переменную типа GameObject и назовем ее thePrefab. Модификатор public требуется указывать, если, например, вы хотите передавать значение переменной через Inspector View. После чего в теле функции Start() создадим еще один GameObject (с именем instance) и проинициализируем его значением с помощью статической функции Instantiate().
Рассмотрим метод Instantiate() подробнее.
Метод клонирует объект original с заданными вектором положения (position) и кватернионом поворота (rotation).
Тип Vector3 является обычным 3х компонентым вектором (аналогично вектору из R 3 ).
Тип Quaternion — кватернион, задающий поворот объекта.
Добавьте скрипт к пустому объекту (c именем GameObject).Напоминаю, поскольку thePrefab объявлен с модификатором public, вы можете задавать его начальное значение прямо в Inspector View (у соответствующего компонента, то есть в нашем случае это Creator у GameObject’а). Перетащите наш префаб в место указания значения (или выберете его из списка, кликнув на кружок справа). 
Нажмем Play и увидим, что на сцене появился наш прыгающий кубик. 
Но наш кубик прыгает просто вверх и вниз, потому что не имеет начального угла поворота. Выберите GameObject и поверните его под небольшим углом.
Теперь, нажав Play, вы увидите, что кубик падает и отталкивается под различными углами. 
Дополнительные материалы:
Базовый Урок 06 — Простой таймер
В данном уроке рассказывается как в Unit при помощи скриптов
создавать простой таймер, используя Time.deltaTime и переменную типа float.
Воспользуемся сценой из предыдущего урока (с пустым игровым объектом,
генерирующим экземпляры префаба, т.е. BouncyBox). 
Создадим С#-скрипт и назовем его Timer. Добавим переменную myTimer, и напишем следующий код.
Сохраняем скрипт и переключаемся назад в Unity. Добавим скрипт к объекту GameObject. 
Напомню, т.к. myTimer объявлена открытой (public), то в Inspector View вы можете менять ее начальное значение.
Жмем Play. Как только значение myTimer упадет до нуля, в статус баре вы увидите строку GAME OVER. Значение переменной myTimer будет продолжать опускаться (это можно увидеть в Inspector View). 
Для того, чтобы переменная myTimer не опускалась ниже нуля, добавим еще одно ветвление в функцию Update(), в итоге мы получаем следующий код:
Нажмем Play и проследим за поведением переменной myTimer. Когда ее значение будет достаточно близким к нулю, то оно перестанет изменяться. 
Дополнительные материалы:
Базовый Урок 07 — Основы движения
В уроке рассказывается, как двигать объекты c помощью функции transform.Translate.
Создадим сцену с кубом, камерой и источником света. 
Создадим новый C#-скрипт и назовем его Move.
Поскольку движение должно быть непрерывно во времени, то основной код будет располагаться в методе Update(). Вызовем функцию Translate, объекта transform и передадим ей в качестве параметра Vector3(0, 0, 1). Получим следующий код:
Разберемся подробнее в коде. Тут transform — это объект класса Transform, привязанный к нашему объекту. Метод Translate() двигает объект вдоль вектора на расстояние равное его длине (параллельный перенос).
Сохраним наш скрипт и добавим его к нашему кубу. Нажмите Play и увидите как куб стремительно улетает вдоль оси Oz.

Давайте уменьшим скорость движения, например, умножив наш вектор на Time.deltaTime, то есть:
Нажмите Play и убедитесь, что куб начинает двигаться заметно медленнее.
Можно сделать наш скрипт более удобным в использовании, если скорость задать не фиксированным вектором, а через переменную. Заведем public переменную типа float и назовем ее speed. С помощью этой переменной можно будет задавать начальную скорость через Inspector View (по умолчанию она будет равна 5.0f):
Сохраним скрипт и убедимся, что в Inspector View у компонента Move появилась переменная Speed. 
Посмотрите, как будет меняться скорость движения нашего объекта в соответствии с заданным начальным значением этой переменной. Например, при Speed = 3 скорость объекта не очень быстрая, но и не медленная.
Примечение: Для выражения Vector3(0.0f, 0.0f, 1.0f) существует короткая (но видимо чуть более медленная, если не прав, прошу поправить) запись Vector3.forward.
Кусок кода из обертки:
Дополнительные материалы:
Базовый Урок 08 — Основы движения с помощью силы.
В уроке рассказывается как c помощью приложения силы двигать физическое тело (Rigidbody).
Если у вас на сцене есть объект с компонентом Rigidbody, то нужно задавать ему движение с помощью приложения силы (передав таким образом все расчеты движения физическому движку игры). В противном случае вы можете начать конфликтовать с физикой объекта. Мы по-прежнему используем сцену из Базового урока 03.

Создадим C#-скрипт и назовем его Force. В методе Start() вызовем метод AddForce() компонента rigidbody (cвязанного с нашим объектом) и передадим ему вектор приложенной силы Vector3(0.0f, 0.0f, power). В классе заведем переменную типа float с именем power и значением, по умолчанию равным 500.0f:
Сохраним скрипт и добавим его к нашему объекту (или префабу). Теперь, если нажать Play, вы увидите как куб падает не вниз а под углом, из-за воздействия силы приложенной вдоль оси Oz. 