unity 导入 obj 模型 和 json 数据

首先 弄了一个导出 obj 模型的脚本 链接如下:

链接:https://pan.baidu.com/s/1rqEyM4RxZEApJkKPKhu3Ng 
提取码:fq4t

把该脚本存放在 Editor/Scripts 文件夹下  就可以把模型导出成为 obj 格式

操作:选中物体 custom--> Export --> Export whole selection to single Obj 

结果:在项目文件夹里,有一个 ExportedObj 文件夹 所产生的 obj 文件 全在里面存放

unity 导入 obj 模型 和 json 数据_第1张图片

obj文件的数据 用json文件记载 格式如下:


  "atlasOption": {
    "maxSize": 2048,
    "pixelPerUnit": 10
  },
  "geometrics": [
    {
      "obj": "1.obj",
      "instanceNum": 6
    },
    {
      "obj": "2.obj",
      "instanceNum": 7
    },
    {
      "obj": "3.obj",
      "instanceNum": 10
    }
  ]
}

用 C# 脚本对 json 读取类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using LitJson;

public class JSONLoader
{
    private Root root;

    public Root load(string path)
    {
        path = Path.Combine(path, "input.json");

        StreamReader streamreader = new StreamReader(path);    // 读取数据 转换成数据流

        JsonReader js = new JsonReader(streamreader);    // 再转换成json数据

        this.root = JsonMapper.ToObject(js);    // 读取

        return this.root;
    }
}

 其 记录 json 的数据结构:

using System.Collections.Generic;

public class AtlasOption
{
    /// 
    /// 
    /// 
    public int maxSize { get; set; }
    /// 
    /// 
    /// 
    public int pixelPerUnit { get; set; }
}

public class GeometricsItem
{
    /// 
    /// 
    /// 
    public string obj { get; set; }
    /// 
    /// 
    /// 
    public int instanceNum { get; set; }
}

public class Root
{
    /// 
    /// 
    /// 
    public AtlasOption atlasOption { get; set; }
    /// 
    /// 
    /// 
    public List geometrics { get; set; }
}

 实现对 外部 obj json 进行 文件转移 到 Assets/Resources 目录下:

using UnityEngine;
using UnityEditor;
using System.IO;
using System;
public static void loadModel()
    {
        //读取
        string path = EditorUtility.OpenFolderPanel("载入模型文件夹", "", "");
        JSONLoader loader = new JSONLoader();
        
        //读取JSON文件
        root = loader.load(path);
        
        // 目标文件夹
        string targetPath = Application.dataPath + "/Resources";
        if (!Directory.Exists(targetPath))
            Directory.CreateDirectory(targetPath);

        // 对每个 geometrics 进行 文件传输
        for (int i = 0; i < root.geometrics.Count; i++)
        {
            // 文件源
            string fileName = path + "/" + root.geometrics[i].obj;
            FileInfo file = new FileInfo(fileName);
            
            // 目标文件 路径
            string targetFilePath = targetPath + "/" + root.geometrics[i].obj;

            // 文件传输 
            file.CopyTo(targetFilePath, true);
        }


    }

你可能感兴趣的:(c#,unity)