Moho to Unity3D, improved .fbx import script

Have you come up with a good Moho trick? Need help solving an animation problem? Come on in.

Moderators: Fahim, Distinct Sun, Víctor Paredes, erey, Belgarath, slowtiger

Moho to Unity3D, improved .fbx import script

Postby the_royal_orchestra » Thu Feb 23, 2017 5:03 pm

Hi,
I was a bit disappointed how the .fbx Files exported from Moho appear in Unity.
The provided import script from the extras folder makes it impossible to place characters in a 3D-Scene and if several .fbx files are imported they intersect randomly. So I improved the import script today by mapping the layer order of Moho to the sortingOrder inside Unity's sortingLayers. (The original script manipulates the drawing order of the materials).

To correct the drawing order in a 3D Scene based on the distance of the characters to the camera I wrote another script that has to be applied to the characters in the scene. Now it is possible to place characters in front or behind each other. This script also corrects the drawing of switch layers. It just switches on the first layer of every switch layer and turns off the others. I found that almost always no switch layer is visible at all in Moho's .fbx exports( inside the .fbx's animations they still work good.)
The script corrects the drawing order for the scene view in edit mode, and switches to correct the game view in play mode.
I don't know if it is possible to correct both at the same time.

Since I'm no programmer and these are my first c#-Scripts please suggest better ways of doing things.

Import script for Editor folder:
https://drive.google.com/open?id=0ByVfkxBnSX-AM1hjWV82SlJfTU0

script to apply to Moho .fbx gameObjects:
https://drive.google.com/open?id=0ByVfkxBnSX-AWmNHcE9velliZ1k

have fun!

MohoFBXImporter.cs
Code: Select all
using UnityEngine;
using UnityEditor;
using System;

// place in Editor folder

public class AnimeStudioPostProcessor : AssetPostprocessor
{
   private bool fIsAnimeStudioModel = false;

   void OnPreprocessModel()
   {
      fIsAnimeStudioModel = false;
      // resampleRotations only became part of Unity as of version 5.3.
      // If you're using an older version of Unity, comment out the following block of code.
      // Set resampleRotations to false to fix the "bouncy" handling of constant interpolation keyframes.
      try
      {
         var importer = assetImporter as ModelImporter;
         importer.resampleRotations = false;
      }
      catch
      {
      }
   }

   void OnPostprocessGameObjectWithUserProperties(GameObject g, string[] names, System.Object[] values)
   {
      // Only operate on FBX files
      if (assetPath.IndexOf(".fbx") == -1)
      {
         return;
      }

      for (int i = 0; i < names.Length; i++)
      {
         if (names[i] == "ASP_FBX")
         {
            fIsAnimeStudioModel = true; // at least some part of this comes from Anime Studio
            break;
         }
      }
   }

   void OnPostprocessModel(GameObject g)
   {
      // Only operate on FBX files
      if (assetPath.IndexOf(".fbx") == -1)
      {
         return;
      }

      if (!fIsAnimeStudioModel)
      {
         //Debug.Log("*** Not Moho ***");
         return;
      }

      Shader shader = Shader.Find("Sprites/Default");
      if (shader == null)
         return;

      Renderer[] renderers = g.GetComponentsInChildren<Renderer>();

      foreach (Renderer r in renderers)
      {
         int renderOrder = 0;
         if (r.name.Contains("|"))
         {
            string[] stringSeparators = new string[] {"|"};
            string[] parts = r.name.Split(stringSeparators, StringSplitOptions.None);
            int j;
            if (Int32.TryParse(parts[parts.Length - 1], out j))
               renderOrder = j; //was += j
         }
         r.sharedMaterial.shader = shader; // apply an unlit shader

         /* use sortingOrder on the default Layer instead of r.sharedMaterial.renderQueue
          * sortingLayers are used not only by the Sprite Renderer:
          */
         r.sortingOrder = renderOrder;

      }
   }
}


MohoFBX.cs
Code: Select all
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System;

[ExecuteInEditMode]

// apply to Moho .fbx GameObjects in the scene

public class MohoFBX : MonoBehaviour {

   private Vector3 cam ;
   private Renderer[] allRs;
   public bool SceneViewCam = true;
   // Use this for initialization
   void Start () {

      // show the first layer of every switching layer

      if (Application.isEditor == true) {

         Transform[] allT = GetComponentsInChildren<Transform> ();
         foreach (Transform t in allT) {


            if (t.childCount > 0) {
               Transform child = t.GetComponentInChildren<Transform> ().GetChild (0);
               if (child.localScale == new Vector3 (0.000001f, 0.000001f, 0.000001f)) {

                  child.transform.localScale = new Vector3 (1f, 1f, 1f);

                  // don't show the other layers

                  for (int i = 1; i < t.childCount; i++) {

                     Transform otherChild = t.GetComponentInChildren<Transform> ().GetChild (i);
                     otherChild.transform.localScale = new Vector3 (0.000001f, 0.000001f, 0.000001f);
                  }
               }
            }
         }
      }



   }

   // Update is called once per frame
   void Update () {

      // use main Camera to calculate drawing order
      cam = Camera.main.transform.position;

      // this corrects drawing the Scene view if not playing:
      if (Camera.current != null && Application.isPlaying == false && SceneViewCam == true) {
         cam = Camera.current.transform.position;
      }

      // draw in layers in order but also use distance from camera

      float dist2cam = Vector3.Distance (cam, transform.position) * -100;

      Renderer[] allRs = GetComponentsInChildren<Renderer> ();
      foreach (Renderer r in allRs) {

         int renderOrder = 0;
         if (r.name.Contains("|"))
         {
            string[] stringSeparators = new string[] {"|"};
            string[] parts = r.name.Split(stringSeparators, StringSplitOptions.None);
            int j;
            if (Int32.TryParse(parts[parts.Length - 1], out j))
               renderOrder = j + (int)dist2cam;
         }


         r.GetComponent<Renderer> ().sortingOrder = renderOrder;
      }

   }
}



And here is an additional optional Editor script that applies changing the drawing mode (game view / scene view) in one MohoFBX object to all others in the scene automatically:

MohoFBXInspector.cs
https://drive.google.com/open?id=0ByVfkxBnSX-ARl9JSnY4Vnh4b1U

Code: Select all
using UnityEditor;
using UnityEngine;
using System.Collections;

// place this script in Editor folder
// move an object to update if it does not redraw by itself instantly

// Custom Editor using SerializedProperties.
// Automatic handling of multi-object editing, undo, and prefab overrides.
[CustomEditor(typeof(MohoFBX))]
[CanEditMultipleObjects] // not really needed here
public class updater : Editor {
   SerializedProperty useAllSceneViews;


   void OnEnable () {
      // Setup the SerializedProperties.
      useAllSceneViews = serializedObject.FindProperty ("SceneViewCam");

   }

   public override void OnInspectorGUI() {
      // Update the serializedProperty - always do this in the beginning of OnInspectorGUI.
      serializedObject.Update ();

      // Show the custom GUI controls.
      EditorGUILayout.PropertyField (useAllSceneViews, new GUIContent("Game / Scene View") );

      //  find all MohoFBX objects and change their drawing mode, too:
      MohoFBX[] mohoFBXs = (MohoFBX[])GameObject.FindObjectsOfType (typeof(MohoFBX));
      foreach (MohoFBX m in mohoFBXs) {
         m.SceneViewCam = useAllSceneViews.boolValue;
      }
         

      // Apply changes to the serializedProperty - always do this in the end of OnInspectorGUI.
      serializedObject.ApplyModifiedProperties ();

   }


}
Last edited by the_royal_orchestra on Fri Feb 24, 2017 1:13 am, edited 1 time in total.
the_royal_orchestra
 
Posts: 9
Joined: Tue Feb 14, 2017 1:24 am

Re: Moho to Unity3D, improved .fbx import script

Postby dkwroot » Thu Feb 23, 2017 7:23 pm

This is fantastic! Thank you for making this.
User avatar
dkwroot
 
Posts: 616
Joined: Thu May 02, 2013 6:56 am
Location: USA

Re: Moho to Unity3D, improved .fbx import script

Postby the_royal_orchestra » Fri Feb 24, 2017 12:32 pm

Just updated the downloadable files.
Now it is possible to set the camera used to calculate the sorting order with the Inspector.
The repair mechanism of switch layers is a bit smarter now.
It does not correct animations, though-
If the fbx exporter of Moho fails somehow, try adding keyframes on frame 1.

I could not figure out how to update the scene view yet.
After you orbit around in scene view, or switching from game view mode you have to move an object to redraw everything correctly.
There is " SceneView.RepaintAll(); ", but I couldn't get it to work properly. Does someone have a clue?
the_royal_orchestra
 
Posts: 9
Joined: Tue Feb 14, 2017 1:24 am

Re: Moho to Unity3D, improved .fbx import script

Postby the_royal_orchestra » Sat Feb 25, 2017 5:37 pm

Here is an update that also corrects the visibility of Layers which are affected by more than one bone (Flexi-bind,..).
The corrections also work on animations now.
Make sure to place a freeze pose keyframe when you set a layer visible again in an animation.
Since the corrections may have unwanted side-effects (?) it is possible to turn them off from the inspector.

https://drive.google.com/open?id=0ByVfkxBnSX-AR054WWZ1X2ZhSTA
the_royal_orchestra
 
Posts: 9
Joined: Tue Feb 14, 2017 1:24 am

Re: Moho to Unity3D, improved .fbx import script

Postby hano » Mon Mar 06, 2017 9:59 pm

Thanks man, I'll try this one for sure.
I wish we didn't have to go through this.
Maybe Smith Micro can pay you to help them out once things are better for them.
hano
 
Posts: 27
Joined: Sun Jan 01, 2017 7:37 pm

Re: Moho to Unity3D, improved .fbx import script

Postby the_royal_orchestra » Sat Apr 01, 2017 11:44 am

Yeah, pay me :-)
the_royal_orchestra
 
Posts: 9
Joined: Tue Feb 14, 2017 1:24 am

Re: Moho to Unity3D, improved .fbx import script

Postby Gogi » Sun Jan 07, 2018 2:07 pm

Hey Guys.
I'm absolutely new to all of this.
Hope my question doesn't sound silly but where does MohoFBX.cs goes? Where do you place it?
And one more question - when I put the MohoFBXImporter.cs to Unity Editor folder, it does solve the layer order of the object but the order of all objects in Unity isn't working right. Some objects aren't visible through others (even though I gave one object Z position 0.002 and the other Z position 0.001, some parts of "object 0.002" aren't visible through "object 0.001"). Do you know where is the problem?

Thank you a lot :)
Gogi
 
Posts: 1
Joined: Sun Jan 07, 2018 2:49 am


Return to Tips & Techniques

Who is online

Users browsing this forum: No registered users and 2 guests