unity static gameobject что это

Static GameObjects

If a GameObject The fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary does not move at runtime, it is known as a static GameObject. If a GameObject moves at runtime, it is known as a dynamic GameObject.

Many systems in Unity can precompute information about static GameObjects in the Editor. Because the GameObjects do not move, the results of these calculations are still valid at runtime. This means that Unity can save on runtime calculations, and potentially improve performance.

The Static Editor Flags property

The Static Editor Flags property lists a number of Unity systems which can include a static GameObject in their precomputations. Use the drop-down to define which systems should include the GameObject in their precomputations. Setting Static Editor Flags at runtime has no effect on these systems.

You should only include a GameObject in the precomputations for systems that need to know about that GameObject. Including a GameObject in the precomputations for a system that does not need to know about that GameObject can result in wasted calculations, unnecessarily large data files, or unexpected behavior.

The Static Editor Flags property is located in the Inspector A Unity window that displays information about the currently selected GameObject, Asset or Project Settings, alowing you to inspect and edit the values. More info
See in Glossary for a GameObject, in the extreme top-right. It comprises a checkbox, which sets the value to Everything or Nothing, and a drop-down menu that lets you choose which values to include.

Источник

Static GameObjects

If a GameObject The fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary does not move at runtime, it is known as a static GameObject. If a GameObject moves at runtime, it is known as a dynamic GameObject.

Many systems in Unity can precompute information about static GameObjects in the Editor. Because the GameObjects do not move, the results of these calculations are still valid at runtime. This means that Unity can save on runtime calculations, and potentially improve performance.

The Static Editor Flags property

The Static Editor Flags property lists a number of Unity systems which can include a static GameObject in their precomputations. Use the drop-down to define which systems should include the GameObject in their precomputations. Setting Static Editor Flags at runtime has no effect on these systems.

You should only include a GameObject in the precomputations for systems that need to know about that GameObject. Including a GameObject in the precomputations for a system that does not need to know about that GameObject can result in wasted calculations, unnecessarily large data files, or unexpected behavior.

The Static Editor Flags property is located in 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 for a GameObject, in the extreme top-right. It comprises a checkbox, which sets the value to Everything or Nothing, and a drop-down menu that lets you choose which values to include.

Источник

GameObject

GameObjects are the fundamental objects in Unity that represent characters, props and scenery. They do not accomplish much in themselves but they act as containers for Components, which implement the real functionality.

For example, a Light object is created by attaching a Light component to a GameObject.

A simple Cube GameObject with several Components

A solid cube object has a Mesh Filter and Mesh Renderer component, to draw the surface of the cube, and a Box Collider component to represent the object’s solid volume in terms of physics.

A simple Cube GameObject with several Components

Детали

A GameObject always has a Transform component attached (to represent position and orientation) and it is not possible to remove this. The other components that give the object its functionality can be added from the editor’s Component menu or from a script. There are also many useful pre-constructed objects (primitive shapes, Cameras, etc) available on the GameObject > 3D Object menu, see Primitive Objects.

Since GameObjects are a very important part of Unity, there is a GameObjects section in the manual with extensive detail about them. You can find out more about controlling GameObjects from scripts on the GameObject scripting reference page.

Читайте также:  какие тату можно сделать на руке девушке со смыслом

Источник

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

Static Status

Tags and Layers

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 The process of drawing graphics to the screen (or to a render texture). By default, the main camera in Unity renders its view to the screen. More info
See in Glossary or physics collisions.

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.

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.

Читайте также:  tinder что это за сайт

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.

The Primitive shapes available in Unity’s GameObject menu

Источник

Передача данных между сценами в Unity — применение мультисценности в разработке простых игр

Данная статья будет полезна начинающим разработчикам игр. В ней я расскажу о собственном опыте реализации мультисценного взаимодействия и проблемах с которыми я столкнулась.

Поговорим о статических классах для хранения данных, различных способах подгрузки сцен движком Unity, а также коснёмся кейса подключения Admob к проекту. Информация предоставлена официальной документацией и доброжелательным коммьюнити разработчиков.

Ситуация

Моя игра представляет собой две сцены — главное меню, которое видно сразу при загрузке и, непосредственно, игровая сцена с механикой, в которую в зависимости от выбранной опции подгружается префаб объекта. Объединить их в одну сцену мне не представлялось возможным, так как на меню завязано несколько довольно сложных объектов, да и удобнее всё же разделять сущности.

Ранее для хранения данных я бы просто использовала некий объект-контроллер, но с выгрузкой сцены он перестаёт существовать.

Передача данных (static class)

Оказалось, что Unity превосходно умеет работать с кодом, даже если он мирно лежит файликом в папке скриптов и не прикреплён компонентом к объекту на сцене (это было не очевидно для новичка). Например, таким файлом может быть статический класс такого вида:

Таким образом, мне удалось сохранить выбор пользователя даже после выгрузки сцены и загрузки новой. Изначально всё работало именно с жёстким переключением сцен.

С помощью такого механизма можно также передавать в другие сцены настройки из меню, например — язык локализации, настройки звуков и музыки и многое другое.

Мультисценность (SceneManagement)

Меня всё устраивало и так, пока не поступила задача подключить к проекту Admob (рекламу), таким образом, чтобы ролик показывался прямо в начале игровой сцены. Как выяснилось, тут есть тонкости: запрос ролика занимает существенное время, и он просто не успевает прийти при переключении сцен. Лепить дополнительные задержки в проекте не хотелось, тем более, что у нас есть куча времени, пока игрок «залипает» в меню. Тут я и узнала, что переключать сцены «жёстко» нет никакой необходимости, ведь есть замечательная опция аддитивной загрузки (без выгрузки предыдущей сцены).

Подгружаю игровую сцену контроллером меню (сцена с меню и объектом рекламы остаётся загруженной тоже):

По завершению уровня, выгружаю сцену игры игровым контроллером (чтобы не висела в памяти):

С использованием такой схемы, реклама загружается сразу при старте приложения, и вызвать показ рекламного ролика можно в любой нужный момент. Аналогично можно поступать с любыми необходимыми вам объектами.

Проблемы

К сожалению, даже при аддитивной загрузке сцен, не удастся вволю покопаться в объектах одной сцены из другой. Ссылки на объекты придётся передавать через некий «медиатор» (в моём случае использовался тот самый статический класс).

Будьте внимательны при инстанцировании префабов, если активны несколько сцен — у меня они все решили затолкаться в неправильную сцену (об этом в другой раз).

Источник

Информ портал о технике и не только