简体   繁体   中英

How to assign to variable content of Three.js model file

When you export your model from Blender to Three.js you end up with a file with JSON data inside. I know two ways of loading this model from that file:

var loader = new THREE.JSONLoader()
var material = new THREE.MeshPhongMaterial({color: '#8080a0'})

1.

loader.load('tower.json', function (geometry) {
    var mesh = new THREE.Mesh(geometry, material)
})

2. Edit tower.js file and add

var tower = 

in first line. Then you can load it with:

var towerModel = loader.parse(tower)
var mesh = new THREE.Mesh(towerModel.geometry, material)

I like second solution more because using loader.load() function every time you want to create a mesh when you have thousands of meshes based on the same model is very slow and can easly kill your browser.

So my question is - can I get JSON data from tower.json file into a variable without editing the file manually? The best solution would be to get JSON data into a variable without making changes to the file.

I would go for option 1. It sounds very strange to add a loader to a source file. To keep things clean you should keep loaders and data sources (your model files) separated if you ask me.

Why would you reload the same model anyway. You should just store it in a variable and reuse it. It is a waste of CPU and memory to load the same geometry twice.

You can do easily something like this to optimize things. It is just a concept but I hope you get the idea:

// Storage for model files
myFiles = {
    tower: 'tower.json',
    car: 'car.json'
};

// Storage for loaded geometries
myModels = {
    tower: null,
    car: null
};

// Loader, loads only first time from file then from storage
var load = function( modelName ){
    if( myModels[modelName] === null ){
        loader.load(myFiles[modelName], function (geometry) {
            myModels[modelName] = geometry;
        });
    }

    var model = new THREE.Mesh(myModels[modelName], material)
    scene.add( model );
}

You can rework it how you think is best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM