Skip to content

Instantly share code, notes, and snippets.

@FlaShG FlaShG/FBXAxesFixer.cs
Last active Aug 29, 2015

Embed
What would you like to do?
This AssetPostprocessor switches the Y and Z axes of imported FBX files (and everything converted to FBX from Unity).
using UnityEngine;
using UnityEditor;
public class FBXAxesFixer : AssetPostprocessor
{
void OnPostprocessModel(GameObject g)
{
if(assetImporter.ToString() == " (UnityEngine.FBXImporter)")
{
FixFBXImport(g.transform, 0);
}
}
private static void FixFBXImport(Transform t, int depth)
{
var filter = t.GetComponent<MeshFilter>();
bool hasMesh = filter;
/*
* If there is only one object in the file, it will have depth 0.
* If there are more objects, the GameObject at depth 0 will be a non-transformed GameObject created by Unity.
* The root objects of the file will have depth 1 then.
* Every object that is a child of another object in the file will have depth 2 or higher.
*/
if(depth == 0) //Root object
{
if(hasMesh) //If we're looking at the only object in the file
{
t.Rotate(90, 0, 0, Space.Self);
var euler = t.localEulerAngles;
t.localEulerAngles = new Vector3(-euler.x, euler.y, -euler.z);
}
}
else //Children objects
{
if(depth == 1) //Root objects
{
t.Rotate(90, 0, 0, Space.Self);
var euler = t.localEulerAngles;
t.localEulerAngles = new Vector3(-euler.x, euler.y, -euler.z);
var pos = t.localPosition;
t.localPosition = new Vector3(-pos.x, pos.y, -pos.z);
}
else //Children of other objects
{
var euler = t.localEulerAngles;
t.localEulerAngles = new Vector3(-euler.x, euler.z, euler.y);
var pos = t.localPosition;
t.localPosition = new Vector3(-pos.x, pos.z, pos.y);
}
}
//Fix Children too
foreach(Transform child in t)
{
FixFBXImport(child, depth + 1);
}
//Now for the actual mesh
if(!hasMesh)
return;
var mesh = filter.sharedMesh;
var vertices = mesh.vertices;
var normals = mesh.normals;
//Switch y and z axis
var newVertices = new Vector3[mesh.vertexCount];
var newNormals = new Vector3[mesh.vertexCount];
for(int i = 0; i < mesh.vertexCount; ++i)
{
var v = vertices[i];
var n = normals[i];
newVertices[i] = new Vector3(v.x, v.z, v.y);
newNormals[i] = new Vector3(n.x, n.z, n.y);
}
mesh.vertices = newVertices;
mesh.normals = newNormals;
//Fix flipped normals
var tris = mesh.triangles;
for(int i = 0; i < tris.Length; i += 3)
{
var buffer = tris[i];
tris[i] = tris[i + 2];
tris[i + 2] = buffer;
}
mesh.triangles = tris;
//Clean up after work
mesh.RecalculateBounds();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.