"Do something when a value is changed" in Python Node?
Is there a way to perform an action if a value is changed?
The logic would be something like this:
If new value != with the existing value: do something:
Here is the existing code (inside of a Python node in an Expresso)
import c4d #Welcome to the world of Python def main(): store_value = 0 # The value ranges from 0 or 1 if Input1 != store_value: print "Something changed" store_value = Input1 else: print "Nothing changed"
The problem is at next draw/redraw/refresh the store_value stays at zero even though the Input is already at 1. This means the
store_value = Input1is not working.
You can check the illustration file here:
Upon opening the file, you'll see in the console printing "Nothing Changed" repeatedly. Now if you change the user data. It prints "Something Changed" but then it continuously prints "Something is changed".
The result should be something like
Nothing Changed # Changes user data Something changed # Back to Nothing Changed Nothing Changed
Is there a way around this? Thank you for looking at the problem
m_adam last edited by m_adam
Hi @bentraje the way to go is to use a global variable. This will define a variable in the global space of the current node that will be frame independent and will live as long as the node itself live.
import c4d global store_value store_value = 0 def main(): if not c4d.threading.GeIsMainThread(): return global store_value if Input1 != store_value: print "Something changed" store_value = Input1 else: print "Nothing changed"
Thanks for the response. I tried the code but I still get the same result.
Nothing changed first.
Then something changed all throughout.
You can see the revised file here:
m_adam last edited by
Sorry, I edited the code, the main issue is that you defined each time the new value to 0.
No worries. Thanks again for the reply!
Just one last thing:
Is there a way to save the store_value when closing and then reopening the file?
The current set-up is
user_data value = 0.
When you change the value from 0 to 1. It works perfectly (i.e. prints something is changed)
However, when the set-up is the
user_data value = 1(the user changed it in the last session),
and change the value from 1 to 0, it prints "Nothing changed" where it should be "Something changed".
Not sure if this is possible since
store_value=0is hard coded. Or do you have any alternative to the set-up? I'm all ears! Thank you
m_adam last edited by
Hi sorry I overlooked your answers.
If you want to have something more consistent you should store it into the scene. So the things that make more sense is to store it into the basecontainer of the current GvNode. Like so
import c4d def main(): if not c4d.threading.GeIsMainThread(): return bc = op.GetDataInstance() # Get an unique ID at https://plugincafe.maxon.net/c4dpluginid_cp store_value = bc if Input1 != store_value: print "Something changed" bc = Input1 else: print "Nothing changed"