import an fbx file at runtime in unity in csharp

To import an FBX file at runtime in Unity, you'll need to load the file as an assetbundle or resource. Here's an example of how to do it:

main.cs
using UnityEngine;

public class ImportFBX : MonoBehaviour
{
    public string filePath; // The path to the FBX file
    public string assetName; // The name of the asset in the FBX file

    void Start()
    {
        // Load the asset bundle
        AssetBundle assetBundle = AssetBundle.LoadFromFile(filePath);

        if (assetBundle == null)
        {
            Debug.Log("Failed to load AssetBundle!");
            return;
        }

        // Load the FBX file as a GameObject
        GameObject prefab = assetBundle.LoadAsset<GameObject>(assetName);

        if (prefab == null)
        {
            Debug.Log("Failed to load asset!");
            return;
        }

        // Instantiate the GameObject
        Instantiate(prefab);

        // Unload the asset bundle to save memory
        assetBundle.Unload(false);
    }
}
841 chars
35 lines

Alternatively, you can also load the FBX file as a resource using the Resources.Load function. To do this, move the FBX file to a folder named "Resources" in your Assets directory, and use the following code:

main.cs
using UnityEngine;

public class ImportFBX : MonoBehaviour
{
    public string assetName; // The name of the asset in the FBX file

    void Start()
    {
        // Load the FBX file as a GameObject
        GameObject prefab = Resources.Load<GameObject>(assetName);

        if (prefab == null)
        {
            Debug.Log("Failed to load asset!");
            return;
        }

        // Instantiate the GameObject
        Instantiate(prefab);
    }
}
460 chars
22 lines

Note: Unity only supports FBX files that are exported in the ASCII format, not the binary format.

gistlibby LogSnag