Giakaama
(Giakaama)
June 17, 2014, 6:03am
1
Hello, I’m trying to do a simple script, something like this.
import bpy
bpy.ops.view3d.snap_cursor_to_selected()
bpy.ops.object.editmode_toggle()
bpy.ops.object.origin_set(type=‘ORIGIN_CURSOR’)
I’m writing this in the text editor in Blender, but when I Run Script it gives me “Python script fail, look in the console for now …”
And nothing more.
When I write the Console
import bpy
bpy.ops.view3d.snap_cursor_to_selected()
I get this:
bpy.ops.view3d.snap_cursor_to_selected()
Traceback (most recent call last):
File “<blender_console>”, line 1, in <module>
File “C:\Program Files\Blender Foundation\Blender\2.71\scripts\modules\bpy\ops.py”, line 188, in call
ret = op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.view3d.snap_cursor_to_selected.poll() failed, context is incorrect
What am I doing wrong, because I’ve seen some videos that they only write what I’ve written in the text editor and works ?
Thanks
CoDEmanX
(CoDEmanX)
June 17, 2014, 5:27pm
2
If you run it from text editor, the context is “text editor”, but the operator requires a 3d view context.
You don’t really need these operators, you can do it even without mode switching:
import bpy
import bmesh
from mathutils import Vector, Matrix
ob = bpy.context.object
#ob.update_from_editmode()
mat = ob.matrix_world
me = ob.data
bm = bmesh.from_edit_mesh(me)
v = [v.co for v in bm.verts if v.select]
#v = [v.co for v in me.vertices if v.select]
loc = mat * (sum(v, Vector()) / len(v))
#print(loc)
#bpy.context.scene.cursor_location = loc
mat.translation = loc
#me.transform(Matrix.Translation(-loc))
bm.transform(Matrix.Translation(-loc))
bmesh.update_edit_mesh(me, False, False)
1 Like
Giakaama
(Giakaama)
June 18, 2014, 12:35am
3
Thanks for the code, but I just wanted to do a simple operation, something like:
When I’m in Edit Mode - I select a vertice
Run the Script that puts 3D Cursor To the Selected Vertice
Tabs out of Edit Mode
Sets the origin to the 3D Cursor
This is what I wanted :), but ty for the script maybe I’ll need it sometime.
PythonFan
(PythonFan)
July 22, 2014, 1:05pm
4
If you run this command from the Blender text editor:
import bpy
bpy.ops.view3d.snap_cursor_to_selected()
You get an error message:
RuntimeError: Operator bpy.ops.view3d.snap_cursor_to_selected.poll() failed, con
text is incorrect
If you run this command from the Blender text editor:
import bpy
bpy.context.area.type = ‘VIEW_3D’
bpy.ops.view3d.snap_cursor_to_selected()
The cursor is successfully snapped to selected, but your text editor has changed to a 3D view window.
If you run this command from the Blender text editor:
import bpy
bpy.context.area.type = ‘VIEW_3D’
bpy.ops.view3d.snap_cursor_to_selected()
bpy.context.area.type = ‘TEXT_EDITOR’
The cursor is successfully snapped to selected, and your text editor window remains a text editor window.
1 Like
Hi PythonFan,
thank you for your code.
Only one note: you must use a ’ instead of a ’ to mask ‘VIEW_3D’.