Mei Zhang
Mei Zhang

Reputation: 1714

How to update mesh data via blender python script?

I can create a mesh in blender with this script:

mesh = bpy.data.meshes.new("mymesh")
obj = bpy.data.objects.new("myobj", mesh)
bpy.context.scene.collection.objects.link(obj)
mesh.from_pydata([[0, 0, 0], [1, 0, 0], [1, 1, 0]], [], [[0, 1, 2]])

However, if I try to update the mesh data with from_pydata again, it results in an error:

RuntimeError: internal error setting the array

Is there a way to update the mesh data after the mesh has been created?
(I'm trying to avoid deleting the object and creating it again with new data.)

Upvotes: 3

Views: 6399

Answers (2)

tschundler
tschundler

Reputation: 2217

Facing this problem, it seems there can be a couple of causes.

  • incorrect formatting or number of verts / faces (eg 2D or 4D vertex)
  • trying to modify an existing mesh

To replace the context of an existing mesh, clearing the existing mesh data works to make from_pydata work again

import bmesh

# reset mesh by copying an empty one
nm = bmesh.new()
nm.to_mesh(obj.data)
nm.free()

obj.data.from_pydata(verts, [], faces)

Upvotes: 1

sambler
sambler

Reputation: 7079

The from_pydata function takes lists of data and creates a mesh data block. Once you have the mesh data block you can adjust the mesh properties directly. These can be found in the vertices, edges and polygons properties of the mesh data.

obj.data.vertices[0].co.x = 1.25

Mostly this data should not be directly altered, any changes made while in edit mode will get overwritten as the edit mesh is stored as bmesh data. The bmesh module provides faster access and methods to alter mesh data and can also update the mesh while in edit mode.

Upvotes: 0

Related Questions