Как объединить объекты в юнити

от admin

Manually combining meshes

You can manually combine multiple meshes into a single mesh The main graphics primitive of Unity. Meshes make up a large part of your 3D worlds. Unity supports triangulated or Quadrangulated polygon meshes. Nurbs, Nurms, Subdiv surfaces must be converted to polygons. More info
See in Glossary as a draw call optimization technique. Unity renders the combined mesh in a single draw call instead of one draw call per mesh. This technique can be a good alternative to draw call batching in cases where the meshes are close together and don’t move relative to one another. For example, for a static cupboard with lots of drawers, it makes sense to combine everything into a single mesh.

Warning: Unity can’t individually cull meshes you combine. This means that if one part of a combined mesh is onscreen, Unity draws the entire combined mesh. If the meshes are static and you want Unity to individually cull them, use static batching A technique Unity uses to draw GameObjects on the screen that combines static (non-moving) GameObjects into big Meshes, and renders them in a faster way. More info
See in Glossary instead.

unity3d
Объединение объектов

Иногда, когда вы делаете игру, вам нужно создавать и уничтожать много объектов одного и того же типа снова и снова. Вы можете просто сделать это, сделав сборку и инстанцируйте / уничтожьте это, когда вам нужно, однако, это неэффективно и может замедлить игру.

Один из способов обойти эту проблему — объединение объектов. В основном это означает, что у вас есть пул (с или без ограничения количества) объектов, которые вы собираетесь использовать повторно, когда это возможно, чтобы предотвратить ненужное создание или уничтожение.

Ниже приведен пример простого пула объектов

Перейдем сначала к переменным

  • GameObject prefab : это сборник, который пул объектов будет использовать для создания новых объектов в пуле.
  • int amount : Это максимальное количество предметов, которые могут быть в пуле. Если вы хотите создать экземпляр другого элемента, и пул уже достиг своего предела, будет использоваться другой элемент из пула.
  • bool populateOnStart : вы можете выбрать заполнение пула при запуске или нет. Это приведет к заполнению пула экземплярами сборника, так что при первом вызове Instantiate вы получите уже существующий объект
  • bool growOverAmount : установка этого значения в true позволяет пулу расти, всякий раз, когда запрашивается сумма в определенный промежуток времени. Вы не всегда можете точно предсказать количество предметов, которые нужно положить в ваш пул, чтобы при необходимости добавить в свой бассейн больше.
  • List<GameObject> pool : это пул, место, где хранятся все ваши экземпляры / уничтоженные объекты.

Теперь давайте посмотрим на функцию Start

В функции запуска мы проверяем, нужно ли заполнять список при запуске и делать это, если prefab была установлена, а количество больше, чем 0 (иначе мы будем создавать бесконечно).

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

Далее, есть функция Instantiate , в которой происходит большая часть магии

Instantiate функция выглядит так же , как и собственное единство по Instantiate функция, кроме сборной уже указана выше в качестве члена класса.

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

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

Третий «шаг» происходит только в том случае, если в пуле нет неактивных элементов, и пул не может расти. Когда это произойдет, запросчик получит нулевой объект GameObject, что означает, что ничего не было доступно и должно быть обработано должным образом, чтобы предотвратить NullReferenceExceptions .

Важный!

Чтобы ваши предметы возвращались в пул, вы не должны уничтожать игровые объекты. Единственное, что вам нужно сделать, это установить их в неактивные и сделать их доступными для повторного использования через пул.

Простой пул объектов

Ниже приведен пример пула объектов, который позволяет арендовать и возвращать заданный тип объекта. Чтобы создать пул объектов, необходим Func для функции create и Action для уничтожения объекта, чтобы предоставить пользователю гибкость. При запросе объекта, когда пул пуст, будет создан новый объект и при запросе, когда пул имеет объекты, тогда объекты удаляются из пула и возвращаются.

Как объединить объекты в юнити

As the name implies, joints attach game objects together. You can only attach 2D joints to game objects which have a Rigibody 2D component attached or to a fixed position in world space.

2D joints all have names ending ‘2D’. A joint named without a ‘2D’ ending is a 3D joint. 2D joints work with game objects in 2D and 3D joints work with game objects in 3D.

(See Details and Hints, below for useful background information on all 2D joints.)

Читать:
Как войти в компьютер без учетной записи майкрософт windows 10

There are different types of 2D joints. See each joint reference page for detailed information about their properties.

Distance Joint 2D — attaches two game objects controlled by rigidbody physics together and keeps them a certain distance apart.

Fixed Joint 2D — keeps two objects in a position relative to each other, so the objects are always offset at a given position and angle. For example, objects that need to react as if they are rigidly connected: They can’t move away from each other, they can’t move closer together, and they can’t rotate with respect to each other. You can also use this joint to create a less rigid connection that flexes.

Friction Joint 2D — reduces both the linear and angular velocities between two game objects controlled by rigidbody physics to zero (ie: it slows them down and stops them). For example; a platform that rotates but resists that movement.

Hinge Joint 2D- allows a game object controlled by rigidbody physics to be attached to a point in space around which it can rotate. For example; the pivot on a pair of scissors.

Relative Joint 2D — allows two game objects controlled by rigidbody physics to maintain a position based on each other’s location. Use this joint to keep two objects offset from each other. For example; a space-shooter game where the player has extra gun batteries that follow them.

Slider Joint 2D — allows a game object controlled by rigidbody physics to slide along a line in space, like sliding doors, for example.

Spring Joint 2D — allows two game objects controlled by rigidbody physics to be attached together as if by a spring.

Target Joint 2D — connects to a specified target, rather than another rigid body object, as other joints do. It is a spring type joint, which you could use for picking up and moving an object acting under gravity, for example.

Wheel Joint 2D — simulates wheels and suspension.

Details and Hints

Constraints

All joints provide one or more constraints that apply to Rigidbody 2D behaviour. A constraint is a ‘rule’ which the joint will try to ensure isn’t permanently broken. There are different types of constraints available but usually a joint will only provide a few of them, sometimes only one. Some constraints limit behaviour such as ensuring a rigid body stays on a line, or in a certain position. Some are ‘driving’ constraints such as a motor that rotates or moves a rigid body object, trying to maintain a certain speed.

Temporarily Breaking Constraints

The physics system expects that constraints do become temporarily broken; the objects may move further apart than their distance constraint tells them, or objects may move faster than their motor-speed constraint. When a constraint isn’t broken, the joint doesn’t apply any forces and does little work. It is when a constraint is broken that the joint applies forces to fix the constraint: So for the ‘driving’ constraints mentioned above, it maintains a distance or ensures a motor-speed. This force, however, doesn’t always instantaneously fix the constraint. Although it usually happens very fast, it can happen over time.

This time lag can lead to joints ‘stretching’ or seeming ‘soft’. The lag happens because the physics system is trying to apply joint-forces to fix constraints, whilst at the same time other game physics forces are acting to break constraints. In addition to the conflicting forces acting on game objects, some joints are more stable and react faster than others.

Whatever constraints the joint provides, the joint only uses forces to fix the constraint. These are either a linear (straight line) force or angular (torque) force.

HINT: Given the conflicing forces acting on joints, it is always good to be cautious when applying large forces to rigid body objects that have joints attached, especially those with large masses.

Permanently Breaking Joints

All joints have the ability to stop working completely (that is break) when a linear force or angular torque force exceeds a specified limit. This is known as ‘__Break Force__’ and ‘__Break Torque__’:

  • If a joint applies linear force, then it has a Break Force option.
  • If a joint applies an angular (rotation) force then it has a Break Torque option.

Both these limits are pre-set to ‘__Infinity__’: This means that they have no limit.

When a Break Force or Break Torque limit is exceeded, the joint is broken and the component deletes itself from its game object.

Ручное Объединение сеток

Вы можете вручную объединить несколько сеток в одну сетку основной графический примитив Unity. Меши составляют большую часть ваших 3D-миров. Unity поддерживает триангулированные или четырехугольные полигональные сетки. Поверхности Nurbs, Nurms, Subdiv должны быть преобразованы в полигоны. Подробнее
См. в Словарь как оптимизация вызовов отрисовки. Unity визуализирует комбинированную сетку за один вызов отрисовки вместо одного вызова отрисовки для каждой сетки. Этот метод может быть хорошей альтернативой пакетной обработке вызовов отрисовки в тех случаях, когда сетки расположены близко друг к другу и не перемещаются относительно друг друга. Например, для статичного шкафа с большим количеством ящиков имеет смысл объединить все в единую сетку.

Похожие статьи