Skip to content

Instantly share code, notes, and snippets.

@jirihnidek
Created March 19, 2015 11:27
Show Gist options
  • Save jirihnidek/2e5218dd8bf06787e538 to your computer and use it in GitHub Desktop.
Save jirihnidek/2e5218dd8bf06787e538 to your computer and use it in GitHub Desktop.
Blender property and callbacks
"""
Example of callbacks used for Blender integer property
"""
import bpy
# Some global values
values = {}
default_value = -1
# Callback function called, when property is changed
def cb_update(self, context):
print('cb_update() my_prop, value: ', self.name, self.my_prop, values)
return None
# Callback function called, when value is requested using obj.my_prop.
# Note: value of property is generated from other source (dictonary in this
# case).
def cb_get(self):
# Do not call self.my_prop inside this callback function, because it will
# cause infinity recursive calling of this function!
print('cb_get() my_prop, value: ', self.name)
try:
value = values[self.name]
except KeyError:
value = default_value
return value
# Callback function called, when new value of property is set using:
# obj.my_prop = 17. Note: Use this function, when you want to
# control the value of property and save it somewhere else (dictionary
# in this case).
def cb_set(self, value):
print('cb_set() my_prop, value: ', self.name, self.my_prop, value)
# Do not do this: self.my_prop = value, because it will cause
# recursive calling of this callback function
values[self.name] = value
return None
# Create new property in object
bpy.types.Object.my_prop = bpy.props.IntProperty(name="MyProp",
default=-1,
description="My Property",
update=cb_update,
get=cb_get,
set=cb_set
)
# Simple tests of callback functions
print(bpy.context.active_object.my_prop)
bpy.context.active_object.my_prop = 10
print(bpy.context.active_object.my_prop)
@jirihnidek
Copy link
Author

This solution is not perfect. There will be serious problem, when e.g.: blend file will be reloaded. There are some useful notes at Blender stack exchange: http://blender.stackexchange.com/questions/27361/duplicating-object-and-default-value-of-property

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment