I have a motion sensor which gives readings, such as position and orientation, of a controller. I receive these readings in a callback function (i.e. event handler function) which looks something like this:
void Readings(Values[] values){ }
where values[0] and values[1] are for the left and right controllers respectively.
If I want to use these readings to move/rotate an object, should I do it in this function or in the Update function?
I didn’t make the sensor/controller, I am just interfacing with them, so I don’t know much about them.
When does the callback occur?
Does it happen on the main thread?
Generally speaking, a callback is better than polling every frame in the Update function however it really depends on how the callback works and when. If it’s happening off the main thread then it’s safer to use the Update method.
Avoid changing values like position or rotation of a transform from other threads. The physics engine may be using or changing them, and Update may execute while the thread is updating, creating a synchronization issue. To keep changes of position and rotation in Unity’s main thread, use Update. It is part of the engine’s timing cycle.
Since we have little information on your sensor, I must assume the callback function is executing in its own thread, otherwise it would have some kind of Unity specific interface that would likely have routed through Unity’s Input class. Use the callback to set static values (or whatever mechanism you devise) to store data coming from the sensors. I assume you merely need the latest incoming data, and you should assume it comes it at a rate probably much faster than Update fires. Have Update read these proposed static values, perhaps declared as volatile (google provides) while making calculations in Update or perhaps FixedUpdate if you’re applying input to physics oriented controls.