3

I am trying to find code for subdividing a plane in Blender 2.8, but I don't find it.

I have just created this code but it doesn't work:

import bpy
import bmesh

plane = bpy.data.objects.get("Plane").select_set(True)

bpy.ops.mesh.subdivide(number_cuts = 1)

Can you help me?

Martynas Žiemys
  • 24,274
  • 2
  • 34
  • 77
MERWYN
  • 31
  • 1
  • 2

2 Answers2

6

bmesh equivalent

Using bmesh can manipulate a mesh in either object or edit mode.

There is generally a bmesh operator equivalent of bpy.ops.mesh... in this case

bmesh.ops.subdivide_edges()

Subdivide Edges.

Advanced operator for subdividing edges with options for face patterns, smoothing and randomization.

An example of 1 cut subdividing all edges of the context objects mesh. Select a mesh object run the script in object mode.

import bpy
import bmesh

context = bpy.context
ob = context.object
me = ob.data
# New bmesh
bm = bmesh.new()
# load the mesh
bm.from_mesh(me)

# subdivide

bmesh.ops.subdivide_edges(bm,
                          edges=bm.edges,
                          cuts=1,
                          use_grid_fill=True,
                          )

# Write back to the mesh

bm.to_mesh(me)
me.update()

To use bmesh in edit mode, load the bound edit mesh, (instead of new and from_mesh)

bm = bmesh.from_edit_mesh(me)

write back (instead of to_mesh)

bmesh.update_edit_mesh(me)

How to use "bmesh.ops.subdivide_edges" on selected edges

Subdividing cubes at different intervals

batFINGER
  • 84,216
  • 10
  • 108
  • 233
3

Assuming this code is being run from a default scene, just after creating a new Plane, your context is incorrect. Subdividing a mesh requires Edit Mode, which can be achieved with the following lines of code:

bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.subdivide(number_cuts=1)
bpy.ops.object.mode_set(mode="OBJECT")

Also keep in mind that your plane object must be the only object selected, and it also must be active.