Главная страница » Как экспортировать модель из blender в unity

Как экспортировать модель из blender в unity

  • автор:

Импортирование объектов из Blender

Unity natively imports Blender files. This works under the hood by using the Blender FBX exporter.

Для того, чтобы начать, сохраните ваш .blend файл в папку Assets вашего проекта. Когда вы переключитесь обратно в Unity, файл автоматически импортируется и отобразится в окне Project .

Для просмотра вашей модели в Unity, перетащите её из окна Project в окно Scene .

Если вы измените ваш .blend файл, Unity автоматически “подхватит” изменения после сохранения.

Unity умеет импортировать

  1. Все узлы с положением, вращением и масштабом. Центры вращения и имена тоже импортируются.
  2. Меши с вершинами, полигонами, треугольниками, UV и нормалями.
  3. Кости.
  4. Skinned меши (меши с привязкой к костям).
  5. Анимации.

См. раздел Использование Blender и Rigify для дополнительной информации о том, как импортировать анимированные персонажи с костями в Unity для использования в Mecanim.

Секреты экспорта из Blender в Unity

— Теория о системе координат (правосторонней и левосторонней)
— Теория правильного создания 3d моделей в blender
— Быстрый экспорт файлов из Blender в Unity3d.
— Как правильно сопоставить масштабы модели в Blender и Unity.
— Экспорт с правильной ориентацией модели
— Почему количество вершин по-разному отображается в Unity и Blender?

Видео к статье

Теория о системе координат (правосторонней и левосторонней)

На самом деле это самая важная часть, я столкнулся с рядом проблем в работе физики 3d модели из-за неправильного экспорта. И так давайте сначала познакомимся с системой координат правосторонней и левосторонней.

Blender использует правостороннюю систему координат с осью Z, направленной вверх. Такую систему координат используют почти все САПР. Смотрите рисунок:

image

Unity3d как почти любой другой игровой движок использует левостороннюю систему координат. Когда Y направлен вверх, X — вбок, Z- вперед. Смотрим рисунок:

image

Теория правильного создания 3d моделей в blender

Для начала надо изучить структуру папок и файлов нашей 3д модели в Blender.
Refence — папка в которой могут хранится вспомогательные чертежи, рисунки, которые помогают построить 3д модель
Textures — папка в которой должны хранится текстуры.
Flags_snow.blend — наша 3d модель в формате blender

Теперь для правильного экспорта 3d модели, мы должны для себя уяснить, что Z+ это будет направление в игре когда объект движется вперед, (Z-) — направление когда объект движется назад. (X+-) это направления поворота вбок — но это в Unity, которая использует левостороннюю систему координат. А в правосторонней системе координат (Blender, 3ds max) Y+ это будет направление когда объект смотрит вперед и (X+-) это направления вбок. Это значит что объект должен стоять в сцене так, как на рисунке, в противном случае ждите проблем с физикой:

Все параметры вращения должны стоять на 0 для дальнейшей работы и для правильной генерации Меша (Mesh), надо Scale установить по умолчанию. Для этого мы сделаем следующие действия в Blender.

1)Выделим все объекты в сцене (клавиша A)
2)Object>Apply>Rotate & Scale.

Теперь все параметры вращения приняты и установлены на 0. А параметры масштабирования (Scale) установлены на по умолчанию (1). Смотрим рисунок:

image

Благодаря пользователю Leopotam, выяснилось что назначать текстуру, лучше в самом Unity3d, а не в Blender, в противном случае, при каждом экспорте FBX файла у вас будет создаваться папка object.fbm (пустая папка которая не на что не влияет, кроме как создает лишний объект в окне Project.

Экспорт с правильной ориентацией модели

Теперь можем делать «Правильный экспорт» из правосторонней системы координат в левостороннюю систему координат.

1)Выделим все объекты (клавиша A)
2)Жмем последовательность R>X>-90.
3)Object>Apply>Rotate.
4)Жмем последовательность R>X>90.

Обязательно делайте в данной последовательности. Далее экспортируем модель в Unity. File>Export>FBX со следующими настройками:

Быстрый экспорт файлов из Blender в Unity3d.

После экспорта модели:
1) Идем в папку с этой моделью и копируем папку Textures (папку с текстурами) и наш FBX файл.

2) Вставляем в папку Assets нашего проект. Это позволит Unity импортировать модель прямо с текстурами, которые были настроены в Blender.

Почему количество вершин по-разному отображается в Unity и Blender?

Как мы видем на рисунке количество вершин (verts) на объекте в Unity3d показывает 28.
Смотрим рисунок:

А количество вершин в Blender = 8

Связано это с тем, что в Unity3d подсчитывается количество вершин самой фигуры и количество вершин в UV развертке:

При создании швов, одна грань разделяется на 2 грани, а следуя математике 1 грань состоит из 2 вершин, следовательно из 2ух граней будет 4 вершины. Для примера воспользуемся Smart UV Project разверткой и установим максимальный Angle Limit.

Смотрим в Blender и количество вершин сократилось с 28 до 24 вершин. Если у кого есть более оптимизированный способ. Пишите в комментариях, обсудим. Некоторые скажут что что сократилось всего на 4 вершины, а представьте если таких объектов 100 или 200, или количество вершин в более детализированных объектах сократиться на 100-300. Помойму не плохой способ оптимизации.

Как правильно сопоставить масштабы модели в Blender и Unity.

Все единицы измерения, что в Blender что в Unity поумолчанию имеет единицу измерения Units. 1 Units= 1 Meter . Поэтому разработчики советуют принимать 1 юнит игрового пространства за 1 реальный метр, и лучше этого придерживаться (хотя бы чтобы с физикой меньше возиться).
И так разберемся с единицами измерения в Blender, в прицнипе в Blender их можно менять, но поумолчанию в Blender используется Units.

Смотрим на рисунок:

Видем параметр Dimension (Измерения или размер). на рисунке мы видем Dimension по X,Y,Z = 1,1,1; следовательно эта фигура куб с размерами 1х1х1 метр. Экспортируем в Unity и переходим на вкладку Inspector

смотрим на параметр Scale Factor, если у вас Unity версии меньше 5, то поумолчанию Scale Factor будет 0.01, исправим этот параметр на 1, если у вас Unity5 то Scale Factor поумолчанию будет 1.

Заключение

Вот и вся статья, как видем экспорт 3d модели из Blender в Unity, это не такуж то и сложно. Для более детального рассмотрения данного материала предлагаю посмотреть видеоуроки в начале статьи >> ссылка

How To Export An FBX To Unity From Blender With Textures?

If you are in the field of game design either as part of a company or as an independent developer then you will likely need to use multiple applications to create the assets for your game or project. This also means that you have to know how to transfer data from one application to another. So how do you export a 3D model as an FBX from Blender to use in your Unity game project?

To export as an FBX from Blender, 1st select the objects that you want to export, then go to File > Export > FBX. In the file browser that pops up set your parameters so that +Y is up and +Z is forward, then define if you want to export parameters, materials etc. Set the asset folder of your Unity project as the destination for the export and click the export button. Then go to Unity and you will see your FBX file in the project folder.

There are many issues that can occur when exporting a model, or collection of models, from one application to another. These issues are normally a result of errors made in Blender either with the object itself or the chosen export parameters. Let’s dive into more detail about how the export process works and what to do if we find any issues.

By the way, if you want to learn more about the different file formats that you can use for exporting assets, check out our article here.

What To Do Before You Export Your Game Model?

If you are exporting a game model for the first time or are just not sure about the process, then we recommend starting off exporting objects to a test project before moving on to the real thing. Before is a short but important checklist of what we need to do before we begin the process of exporting.

Applying The Rotation And Scale Of The Model

The most common issues that can occur are incorrect rotation and scale of the object, which are normally the result of not applying the transforms in Blender. If you look at your object transforms in the side panel, you should see the rotation value set to 0 on all three axes, and the scale values all set to one.

While not as important, keep the location set to 0,0,0 as well and have the geometry close to its origin point. If any of these options are not set to the default values then this will alter the way the model looks when brought into Unity.

To fix this, use the hotkey combination of ‘Control + A’ to bring up the apply menu with the object selected in object mode, you will see a list of transforms that you can apply. Select the option labeled ‘Rotation and Scale’ to apply each of these transforms. Applying Your Transforms

The rotation values of the applied object should now read as 0,0,0 and the scale values should read as 1,1,1 in your side panel, but the appearance of your model should be exactly the same as it was before you applied it.

What If You Are Going To Export An Entire Scene Of Static Objects?

If there are multiple objects in your scene you can export them all in a single FBX file. The process for applying the rotation and scale of the objects is the same, but you would instead select all the objects together and then apply their transforms all at once rather than selecting each object one at a time.

If those objects are static meshes used as part of the scenes environment, then you may not be planning on using those objects in another capacity and may want them in Unity exactly as they are in Blender. In this case, you can apply all the transforms of your meshes so that they all have the location value 0,0,0. This won’t move the object meshes, only the origin points get placed back to the center, which can make things simpler in Unity.

Do You Have A Suitable UV Map For Your Objects?

All solid objects that you will use as potential assets in games will require the use of materials, which can be created either in Blender or in Unity. Most of these will also require textures and as a result, may also require a UV map.

A UV map is a 3D object that is cut apart and mapped out onto a 2D image editor, as a means of being able to more easily map a texture from a png or jpg onto the 3D model.

The UV map needs to be well structured to prevent artifacts on the textures when imported to the game engine. If you are assigning the texture in Blender, you should be able to preview the result before you export and make changes to your UV map where needed.

Use Eevee When Creating Materials For Video Games

Not only can you create objects in Blender but also the materials for those objects as well. Blender has two render engines for previewing how objects appear under user-controlled lighting conditions. If you decide to create materials for your objects in Blender you should use the Eevee render engine to create those materials.

Eevee is an online renderer which means it allows you to view and navigate your scene in real-time without having to wait for the engine to process the image. It achieves this at the cost of realism and the results are generally less spectacular.

However, this is how game engines have to work as well, producing the target image in real time for the end user. The Cycles Engine on the other hand is considered an offline renderer as its focus is on realistic lighting and materials at the cost of render time.

Basically, you should create your materials using the Eevee render engine because it more accurately imitates what you are likely to see in your game engine.

Avoid Using Certain Nodes In Front Of Your Textures

If you have used Blender for any period of time then you will likely be aware of the node system used to create materials. A part of this process involves using texture nodes to create patterns for the materials and plugging them into the primary shader of the material.

It is common to use other nodes as well to adjust your textures and materials in various ways, however having certain nodes in between the texture and the shader can cause issues with the final result, such as with the use of the color ramp.

Why is this the case, well in Unity the textures will come with the model and the material but they will not be automatically applied. We will have to reconnect the shader to the material in Unity itself and that means that anything we have in between the texture and shader nodes in Blender may not carry over.

When creating a material in Blender for use in a game engine, it is recommended to keep the material setup clean and simple as it will all be reconfigured based on the engine that it will be sent to anyway.

Orientate Your Object Correctly

Going back to the model itself if you have an easily identifiable front side for your object (such as with a character model) then you will want to make sure that the model itself is facing forward in Blender.

This is not a strict requirement and is more recommended to prevent confusion when exporting our model to Unity.

For future reference, Blender uses a left handed coordinate system, which means the +Y direction is considered the forward direction, and +Z is the up direction. Unity on the other hand is a right handed coordinate system where +Z is forward and +Y is up. We will deal with this in the export parameters.

Make Sure That All Of Your Objects Normals Are Facing The Correct Way

Along with incorrect transforms this is one of the more common issues that artists and game developers will face when exporting a model from Blender to a game engine like Unity. A normal is a line that is perpendicular to vertex or a set of vertices looped together (face).

The normal defines which side of the vertex, or face, is considered the front side. For objects used in games, normals are very important as the game engine will only render the front side of the geometry, in a process referred to as backface culling.

If the normals of your geometry are facing the wrong way, then you will find parts of your model become invisible when you export it to Unity.

There are multiple ways in which we are able to both identify and deal with incorrect normals in Blender, and you can learn more about it in our article on normals here.

The quickest way to deal with normals though is to select your entire model in edit mode while in Blender, and use the hotkey combo of ‘Alt + N’ to bring up the normals menu and then select the recalculate outside option to fix the normals.

  • Apply Rotation And Scale Of The Objects
  • Apply Location If Exporting A Full Environment
  • Use Eevee To Create And Preview Your Materials
  • Make Sure The Model Has A Usable UV Map
  • Keep Your Materials Nice And Simple
  • Orientate Your Object To Face Forward In Blender
  • Make Certain That All Of Your Object Normals Are Correct

What To Do During The Export Process From Blender?

Once you have gone through the checklist above you should be able to move onto actually exporting your model or your scene. The FBX format is an industry standard method of transferring data of 3D objects even in a professional setting, and so most applications are able to work with this file format.

To export via the FBX method, go to File > Export > FBX to bring up the file browser for the export.

If you do not see the option then it is because the add on for the FBX format is not enabled. Many of the import/export formats are not a part of the base code in Blender and their functionality derives from add-ons that are used to expand on Blender’s core range of tools.

Normally the add-on for importing and exporting FBX files is enabled by default anyway so this should not be a problem. However, if you do not see the option then you can go to Edit > Preferences > Addons and type in FBX in the search bar, then tick the box for the FBX add-on.

You should now be able to export your model as an FBX, so make sure what you want to export is selected and follow the process again to get yourself to the export menu in the file browser.

As you can see from the Image above, you can use other file formats to export your models to Unity. Check out ou article on exporting with these file formats here.

The Parameters In The Side Panel

When the file browser opens for the export you should see a side panel that lists the parameters for your export format, if not move your mouse cursor into the file browser and press the ‘N’ key to make these parameters visible.

Parameters For FBX (Default)

Setting The Path For Textures

The 1st parameter that you will be able to change is the path mode, which references the subdirectories that are connected to the exported object. This basically means the texture maps that are used to create the materials for the base color, roughness, etc, and is an important step for getting your textures into Unity correctly.

The default setting is on auto, but for our recommended method set this option to copy from the drop-down list after you select it. There is also a button that is directly next to the drop down for the path mode. Enable this button so that it is highlighted blue as it will allow you to embed your textures into your FBX file.

The next option below that is for assigning a batch mode. This will divide up your file into smaller files based on the type of batch selected, for example, to save each collection as a single file or even each scene.

This may be useful when exporting entire scenes or environments over but when exporting a small number of objects it’s ideal to keep this option set to off.

Patch Mode Settings

Selecting The Objects That You Want To Export

You then have several tabs that you can access, the first of which is labeled as the ‘Include’ tab and allows you to control what object types will be exported. Click on the label to open up the parameters in the side panel and the first option you will see is to only use selected objects.

We normally have this option ticked and have the objects that we want to export already selected so that we have full control over our export.

You can also limit to the active collection only which is useful if your collection is a series of smaller models that are used to create a larger object.

An example of this would be to create a variety of car parts such as the exhaust and engine and store all of these parts in a collection labeled as ‘car’.

This is useful if the objects of a collection are all related to each other in some way and are a part of a larger object used in Unity.

You can also decide if you want to limit your export based on object types. Again if you have enabled the selection only box then you don’t need to do anything here as your selection will be the only thing exported. If not then you can define what object types you want to export, and this is normally going to be just your armature and mesh objects, as the other object types are not needed since they will be provided by the game engine.

Settings For The Include Tab

Getting The Correct Transforms And Orientation

The next tab allows you to edit the orientation of your model and how the transforms will be converted when the model is exported.

The scale option is set to 1 by default and should be kept this way in most cases.

The apply settings should be kept to the ‘all local’ option.

The forward and up axes should be set to whatever the orientation is for the software that the file will be exported to, in this case, the Unity engine. For the forward direction, we set the axis to positive Z and for the up direction, we set it to positive Y.

Note that this can sometimes result in the correct rotation values of 0,0,0 in unity and sometimes it can import with a Y value of -180 degrees. The problem is that this is inconsistent in that sometimes it is correct and others it isn’t. If you come across the issue then set your forward axis to negative Z to correct it.

Nest we have three tick boxes below, the first is used to take into account the defined units of measurement in Blender for the export. For example, if the size is based on meters in Blender then this will be used to determine the size when imported into Unity.

If Blender units are used instead of metric or imperial measurements then the values will be kept as they are and will be converted in Unity based on the project settings.

The second tick box allows us to use the global space transforms for the object’s rotation data, and the third tick box allows us to bake in the transform data and apply it as the default for our game engine. Normally we would have all three of these boxes ticked to make sure our objects are orientated correctly when imported.

Transform Tab Settings

Setting The Correct Geometry Settings

The Geometry tab controls additional data with regards to our mesh objects’ geometry and structure. We can for example export smoothing data for our normals or for the geometry itself. Normals define the visibility of faces in game engines and it’s important to get these right before hand.

The options below allow us to do things like apply our modifiers or export our subdivision as an FBX subdivision. The preferred workflow here is to apply your Subdivision surface modifier in Blender first and then export with all of these settings as they are, which means having the smoothing set to normals only, and the apply modifiers option as the only ticked box.

Geometry Tab Settings

What If You Have A Rig For Your Model?

If your object is not intended as a static mesh then you will likely have a rig assigned to that mesh so that it can be animated.

An armature is an object type that acts as the parent rig for a mesh model and is therefore required in Unity in order to maintain any animations created using the rig.

Most of the settings in the armature tab are fine as they are, however, the one thing that we recommend changing is the option to add leaf bones which is by default enabled.

We will want to disable this option as leaf bones have no use in a game engine like Unity and so we only end up reporting unnecessary data.

Armature Tab Settings

What About The Animation Tab Then?

The last tab in the export settings is for the animation parameters tied to the mesh object. Not all objects require a rig to animate but all of them require keyframe data.

The tab itself is a checkbox that we can enable or disable, which is handy as static meshes will not require animation data and in these cases, we can turn this tab off entirely.

If your model does have an animation, however, make sure that the box next to ‘bake animation’ is ticked. As for the parameters inside the tab again most of these are fine as they are. The only one that we will probably want to disable it for the NLA strips unless you used them in Blender.

Animation Tab Settings

At this point, you should have gone through everything that you needed to, meaning you can move on to choosing the location for your export.

Where To Export Your FBX Model To?

This is more important than you may think, as sending your FBX to the correct location can really streamline your workflow. We have two recommendations here based on the use case of the FBX file.

Using The FBX For A Single Project?

If your model or collection of models will only be used for a single project, then why not save directly to the project itself and have your models ready to go.

For this to work your Unity project already needs to exist on your system. Every new project will have its own asset folder, so that will be the target for the FBX file. Locate your folder where you store your Unity projects and choose the specific project to send the FBX to.

Open up the folder for the project and you should see a folder labeled as ‘Assets’, select this folder and that will be the location for your exported FBX file. We will need to create some subfolders for our materials, textures, and meshes but we can do that in Unity.

When you are ready to complete the process just click on the Blue button labeled ‘Export FBX’ to finish. Export Location

Using The FBX For Multiple Projects?

In the case of requiring a model for more than one project, we should not export directly to a single project even if it is the one we are currently working on.

Instead, we should find a location that is easy to remember and easy to reach. The first recommended location is the desktop. Simply create a file on your desktop named assets and then save the FBX in that file.

This is preferred if you want to use the FBX file in more than a single application and you need to be able to access the file quickly regardless of the application that you use.

The alternative option is to go to your folder where you store all of your Unity projects and create an assets folder there instead.

This option is best suited for when you want to use the FBX across multiple Unity-based projects as it becomes very easy to find.

When you are ready to complete the process just click on the Blue button labeled ‘Export FBX’ to finish.

Importing Your Model Into Unity

Once you have exported your model from Blender you will then be able to import it into your Unity project. This part is slightly different depending on what location you choose to send your exported FBX file to.

If You Saved Your FBX directly Into The Project Asset Folder…

When you open up your project and go to your asset folder the exported objects will automatically load into your project. You can then drag and drop your model or scene directly into the viewport and begin positioning it, it’s as simple as that.

If You Saved Your FBX In Another Location Other Than Your Asset Folder…

This scenario requires the additional step of importing your FBX file into your current project.

In your asset folder, right click to bring up your options menu and select the option labeled as ‘Import New Asset’, then locate the FBX file and import it into your project.

If everything has been done correctly,, you should see the object appear in your asset folder available for use. If you have any issues, refer to the checklist above and double check that everything has been done correctly.

For example, if you import the FBX but don’t see the model, then you may not have selected it for the export. Import New Asset

Checking That Everything Has Imported Correctly

When you have imported your asset, drag and drop it into your scene and first check to see if the geometry is 100% visible. Don’t worry if the textures don’t show at this point we will deal with them last. The orientation of the object should be correct with the model facing Z forward.

The rotation values should all read as 0,0,0 across the three axis and the scale should be set to 1,1,1. If you have rigged and animated your model you will need to check these as well. Rotation And Scale Of Import

The instanced object in the viewport will not have the animation data visible in the inspector panel. What we will need to do is click on the model in the asset folder to bring up the files import settings.

  • Model
  • Rig
  • Animation
  • Materials

If you select the animation tab, you will have an additional viewport pop up at the bottom of the inspector where you will be able to preview the animation.

As for the materials and textures we need to extract them from the FBX file in order to use them properly and edit them in Unity.

If you have only imported materials and not textures with your model, then some of the basic properties of that material, such as the base color, will be visible on the model. However to get full control we need to extract the materials and textures as we just mentioned.

Import Settings Tabs

Setting Up The Sub Folders In Our Asset Folder

In the asset folder, we will need to create a few additional folders for organizational purposes. To create a new folder right click with the cursor in the asset folder to bring up the options menu. Go to the create option and select ‘folder’ at the top of the list.

Subfolders

Name the new folder as your object folder, to store all of your models in. Then repeat the process two more times, creating a folder for your materials and a folder for your texture maps.

Go back to your exported object and restore the import settings in the inspector, then select the materials tab.

In this tab, you will find two buttons labeled as ‘export materials‘ and ‘export textures‘. First export the materials and send them to the material folder that you created. Then do the same thing you the textures, extracting them to the textures folder.

Textures After Extracting To The Textures Folder

Note that if there are no materials or textures available to be extracted, then these two buttons will appear greyed out.

You should now be able to edit your materials and apply texture maps to them. select an object in your viewport and then click on the little arrow below materials in the inspector, which brings up all the parameters for the material.

You may find that the texture is still not applied and we only see the albedo color. Now though we can go to our texture folder, then drag and drop our albedo map onto the empty square nest to albedo, to assign the texture map to that parameter. The texture should now be visible on the model like it was in Blender.

Material Parameters

We can do this with the other maps as well, for example, we can drag and drop our normal map into our material.

How To Change The Handle Types For Keyframes?

How To Change The Handle Types For Keyframes?

Animating in Blender requires us to not only create keyframes for our animations but also manipulate them by changing the interpolation of those frames and how they interact. The manual

How Does Interpolation Work In The Graph Editor?

How Does Interpolation Work In The Graph Editor?

Animation in Blender requires using keyframes to define the start and end points of an animation based on a changed value. The graph editor allows us to control the animation’s

Creating A Bouncing Ball Animation In Blender?

Creating A Bouncing Ball Animation In Blender?

If you are learning about 3D animation, then one of the first animations that you are likely to create is a bouncing ball. There are several youtube tutorials out there

Blender to Unity — with Correct Rotation & Scale

Blender to Unity - with Correct Rotation & Scale

Have you ever been frustrated when exporting FBX files from Blender and importing them into Unity? Problems with rotation and scaling along the way? In this post I will provide you with some tips and tricks to get the Blender to Unity process working smoother.

First of all, if you are impatient like me, here’s a quick summary of the easiest way to get rotation and scaling right:

For a simple object

(Simple object = no hierarchy and no armature (bones) or animations)

  1. Go to File | Export | FBX (.fbx)
  2. Tick !EXPERIMENTAL! Apply Transform checkbox
  3. Click on Export FBX button

Watch this video (at 1:01) to see it in action

For multiple simple objects

  1. Select an object
  2. Move the the object to position 0,0,0 in your scene if it isn’t there already
  3. Go to File | Export | FBX (.fbx)
  4. Tick Selected Objects checkbox
  5. Tick !EXPERIMENTAL! Apply Transform checkbox
  6. Click on Export FBX button
  7. Go to step 1 and repeat process until all objects are exported

For rigged characters with armature and bones

  1. Select the armature (the mesh should already be a child of the armature)
  2. Rotate the armature to -90 degrees on the X axis
  3. Press Ctrl+A to and select Apply > Rotation
  4. Rotate the armature to 90 degrees on the X axis (do not apply rotation!)
  5. Select the child mesh of the armature containing your character (it should show a rotation of -90 degrees for the X axis)
  6. Press Ctrl+A and Apply Rotation (the X axis rotation should now be 0 for the child mesh object)
  7. Go to File | Export | FBX (.fbx)
  8. If you have nothing else in the scene other than the armature and mesh object you can skip this step, otherwise, select only the armature and the child mesh character object (use shift to select multiple) and tick «Selected Objects» in the FBX export window.
  9. Set Apply Scale dropdown to «FBX Units Scale«
  10. Click the Export FBX button

Watch this video (at 2:24) to see the export process for a rigged character with an armature.

This video highlights the problem and demonstrates the methods to solve the issue:

That’s It.

If you follow the above steps for simple objects and rigged characters, you should end up with correctly rotated and scaled objects when they are imported into Unity with a lot less headache. You’ll even gain some better sleep now!

You can also watch timelapses of the modeling and animation process of the simple lowpoly objects as well as the animated rigged character.

Need More Help?

If you couldn’t quite follow, or if you a more detailed story, not to worry, I’ll fill in the blanks.

There are three main headaches in the workflow of exporting from Blender to Unity: Rotation, Scale, and Animations. I will go through the rotation and scale problem in the remaining part of this post — and I’ll publish a separate post for the Animations problem.

Axis vs. Alignment

Unity works with the Y axis being up/down and Blender works with the Z axis as up/down. This creates a problem.

When you export a FBX file from Blender, regardless of which axis you specify in the blender FBX export settings, the object’s transform will be rotated in Unity. At first, you may not consider this to be a problem because once imported you can drag the object into a scene and it looks correct. But when you look closer at the transform, you’ll notice that the object is rotated automatically by Unity by -90 degrees around the X axis. Plus, the scale is incorrect which will also deal with.

Problem if exporting from Blender using default settings

Problems

  1. The object is rotated around the X axis by -89.98 degrees
  2. The object’s Z axis (blue) is facing upwards (Unity’s Y axis)
  3. The object’s scale is 100

Number 1 (and consequently also number 2) causes a problem because if you try to move the object in it’s forward vector, e.g.:

— this fish won’t swim forward — it will float up like a dead fish along it’s own blue axis.

Number 3, the scale is set to 100. Even though the object is 1 meter in size in the scene — just like the native Unity cube behind it in the picture, it has automatically been scaled up 100 times by Unity in the import process. This must also be fixed because you run into problems of hierarchical scaling if you parent and unparent objects to a scaled object.

Don’t work around the problem

It’s common that people work around this problem by making the object a child of a new GameObject and apply all game logic to the parent — but that is a dirty solution. You would then pollute the scene with potentially unnecessary GameObjects which impacts performance as well as adds complexity. And, you don’t even eliminate the problem to begin with. If you are in the business of making and selling assets for Unity, it is an absolute no-no to have objects with incorrect rotation or scale, nor should you work around the problem with GameObject parenting. Don’t do it.

Fix the problem instead

Assumptions:

  • You have modeled one or more objects in Blender as if 1 Blender unit = 1 Unity unit which both represent 1 meter.
    (If you haven’t, rescale your object and use Ctrl+A to Apply Scale)
  • You have used Blender standard axes for Front/Back/Left/Right/Up/Down.
    (If you haven’t, orient your object and use Ctrl+A to Apply Rotation)
  • You have positioned your object(s) at position 0,0,0 in your Blender scene.
    (If you haven’t, position your object at 0,0,0 and use Ctrl+A to Apply Location)

Fixing the rotation problem «The Easy Way»

The good thing is for a large number of objects — at least all the simple ones — there is an easy fix. When you go to Go to File | Export | FBX (.fbx) you can simply tick the !EXPERIMENTAL! Apply Transform checkbox — and proceed by clicking the Export FBX button in the (upper right corner) to export the object and it should import fine in Unity.

Note: The feature is named !EXPERIMENTAL! for a good reason. It does not work for nested objects, objects with animations, and objects with armatures. Maybe there are also other problems that could arise when using this which is why I am also including an alternative method here to manually fixing the rotation problem.

Again, watch this video (at 1:01) to see it in action.

Fixing the rotation problem «The Manual Way»

If the experimental Apply Transform method does not work for you, for whatever reason, you can do this manually:

  1. Select the object you wish to export
  2. Pres N if you don’t see the transform input fiels
  3. Enter -90 for X Rotation and press Enter
  4. Press Ctrl + A (when mose is over viewport) and Apply > Rotation
  5. Enter 90 for X Rotation and press Enter (do not apply again!)

So what is happening and why does this work when you export the FBX file?

When you rotate the object -90 degrees around the X axis and then you ‘apply’ the rotation — Blender will consider the rotation to be the ‘default rotation’ of the object. So when you rotate the object in step 5 by 90 degrees around the X axis again, and when you don’t apply the rotation, the object’s default rotation is actually pointing in the wrong direction from Blender’s point of view, but in the correct direction from Unity’s point of view. If you were to apply the rotation before exporting, you will be back to where you started which is why it is important that the transform’s rotation in Blender shows as X:90 at the same time as the object is correctly oriented in Blender’s viewport. See the Blender Manual for more details about applying rotation to the transform if needed.

The scale still needs to be fixed — but that is much easier. A simple change of the Apply Scalings dropdown to FBX Units Scale:

So, if the first method (!EXPERIMENTAL! Apply Transform) didn’t work — and you have manually changed the rotation, you can now:

  1. Manually change the rotation as just described above
  2. Go to File | Export | FBX (.fbx)
  3. Tick the Selected Objects if you are exporting a single object
  4. Change Apply Scalings to FBX Units Scale
  5. Click the Export FBX button in the (upper right corner) to export the object and it should import fine in Unity.

The object should now import fine into Unity with correct rotation and scale.

Watch this video (at 1:30) to see «The Manual Way» in action.

But. I have a character with animated armature?

But what about nested objects, such as an armature with a child character mesh? The same principle applies as «The Manual Way» described above, but with these slight modifications:

  1. Rotate the Armature as described in The Manual Way
  2. Apply the Rotation of the Character Child Mesh of the armature

Again, watch this video (at 2:24) to see the export process for a rigged character with an armature.

Is your character scale incorrect to begin with?

If you haven’t got the correct scale of your animated character in Blender, you are in a world of pain my friend. I haven’t found a way to resize the armature without breaking all the animations. You will need to rescale your armature, apply the armature scale, and recreate your animations. If you know of a way to solve this without redoing the animations — please let me know and I will update this post.

Let’s Automate

I have created a Blender Addon that you can download and install. This automates the process of exporting simple objects as individual FBX files ready for import to Unity. The objects that are exported will all be in the correct rotation, scale, and they will be positioned at 0,0,0 regardless of where they are in your Blender scene at the time of export.

You can export hundreds of objects to individual FBX files in a matter of seconds.

Blender Batch FBX Export

You can allow the addon to use different methods to export your objects as FBX files:

  1. Rotated Copy — creates a temporary rotated copy of each object that is positioned at 0,0,0 — then exported and finally removed. The original copy is left as is so you can keep all objects in blender using blender axis and rotations.
  2. Apply Transform — uses the !EXPERIMENTAL! Apply Transform method to export objects. The original copy is left as is so you can keep all objects in blender using blender axis and rotations.
  3. As Is — exports the objects as is, if you have already applied the rotation fix to your objects (either manually or by using the provided «Fix Rotation (Selected Objcts)».

Finally, you can choose to export all (mesh) objects in the scene or your current selection.

To Round Things Off

Thanks for taking your time to read this post. The Blender to Unity rotation and scaling problem has plagued me for years and I never took the time to document the exact settings and behaviors, until now.

If you found this post useful, please share it with the social media icons at the top. Also feel free to link to this post from your web site as it would help it to gain more exposure.

I have a patreon page where you can support future post. As a Tutorial Tier patreon you can also download the .blend files that I created for this tutorial (the fish, stone, single tree, and animated character).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *