• Godot Help
  • Assign obj file to meshinstance in code?

I've created a 3D vehicle already with meshinstances for all the different parts and plugged in all the different obj files and gotten everything working fine. Looking at it I want to be able to select different vehicles but don't really want to manually create a different scene for each one. I was thinking I could simple supply a directory name and standardized obj names then put everything in code so the game automatically builds a scene for each vehicle (Only meshes would look different). Problem is I can't quite figure out how to assign a .obj file to a meshinstance in code (very simple in the inspector of course). Anyone know how?

Source assets like obj or gltf files need to be importer through the editor. However, once they are imported, then can be saved as scenes, and you can load them or move them around like any node. You can also extract the Mesh or MeshInstance and reapply it to another Mesh. I haven't tried it, but it should work that way I think.

Actually it turned out to be simple and straightforward and I've used the method several times in the past - just not with meshes

var Mesh: ArrayMesh

func _ready():
    Mesh = load("res://MyObj.obj")
    mynode = get_node("MyNode") # A meshinstance
    mynode.mesh = Mesh

Now I can work on getting all the files in a directory and use those to build meshes. Each vehicle with it's own directory and identically named files but the files contain the data for that particular vehicle.